Getting the number of dimensions of a multidimensional array in Java
January 21st, 2009
Based on my previous post 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:
Object[] a = new Object[3][0]; System.out.println(getNumberOfDimensions(a));
prints 2.
Object[] a = new Object[1]; a[0] = new float[2][5][1]; System.out.println(getNumberOfDimensions(a));
prints 1.
Here’s the code:
/** * Returns the number of dimensions which a multidimensional * array has as a positive integer. For example, returns 3 * when passed a <code>float[][][]</code> * @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; }