Java - Get Dimension of an Array

Introduction

Java supports an array of arrays.

Class class getComponentType() method returns the Class object for an array's element type.

The following code illustrates how to get the dimension of an array.

Demo

public class Main {
  public static void main(String[] args) {
    int[][][] intArray = new int[5][3][4];

    System.out.println("int[][][] dimension is " + getArrayDimension(intArray));
  }/*from w w w . j a v  a2  s  . com*/

  public static int getArrayDimension(Object array) {
    int dimension = 0;
    Class c = array.getClass();

    // Perform a check that the object is really an array
    if (!c.isArray()) {
      throw new IllegalArgumentException("Object is not an array");
    }

    while (c.isArray()) {
      dimension++;
      c = c.getComponentType();
    }
    return dimension;
  }
}

Result

Related Topic