The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.lang.reflect  [17 examples] > Arrays  [6 examples]

e121. Getting the Length and Dimensions of an Array Object

The length of an array is the number of elements of the array. The dimensions of an array type of int[][][] is three.
    Object o = new int[1][2][3];
    
    // Get length
    int len = Array.getLength(o);  // 1
    
    // Get dimension
    int dim = getDim(o);           // 3
    
    // If `array' is an array object returns its dimensions; otherwise returns 0
    public static int getDim(Object array) {
        int dim = 0;
        Class cls = array.getClass();
        while (cls.isArray()) {
            dim++;
            cls = cls.getComponentType();
        }
        return dim;
    }

 Related Examples
e120. Determining If an Object Is an Array
e122. Getting the Component Type of an Array Object
e123. Creating an Array
e124. Expanding an Array
e125. Getting and Setting the Value of an Element in an Array Object

See also: Constructors    Fields    Methods    Modifiers   


© 2002 Addison-Wesley.