Getting the number of dimensions of a multidimensional array in Java

Based on my [permalink href=”4″]previous post[/permalink] about cloning multidimensional arrays, I have come up with a short static function to get the number of dimensions which a multidimensional array has.

Note that this method only returns the number of dimensions of the original object passed as argument. It does not expand into the contained objects themselves. Example:

[sourcecode language=’java’]
Object[] a = new Object[3][0];
System.out.println(getNumberOfDimensions(a));
[/sourcecode]
prints 2.

[sourcecode language=’java’]
Object[] a = new Object[1];
a[0] = new float[2][5][1];
System.out.println(getNumberOfDimensions(a));
[/sourcecode]
prints 1.

Here’s the code:
[sourcecode language=’java’]
/**
* Returns the number of dimensions which a multidimensional
* array has as a positive integer. For example, returns 3
* when passed a float[][][]
* @param src the multidimensional array
* @return the number of dimensions of src
* @author Philipp Buluschek bulu@romandie.com
*/
public static int getNumberOfDimensions(Object[] src){
int dim = 1;
Class cl = src.getClass().getComponentType();
while(cl.isArray()){
dim++;
cl = cl.getComponentType(); // will not return null as we tested isArray() above
}
return dim;
}
[/sourcecode]


Posted

in

by