Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Dimension length array reflection java

How do I find the length of a multi-dimensional array with reflection on java?

like image 541
Marcos Roriz Junior Avatar asked Nov 19 '09 15:11

Marcos Roriz Junior


People also ask

What is the length of a multidimensional array in Java?

The representation of the elements is in rows and columns. Thus, you can get a total number of elements in a multidimensional array by multiplying row size with column size. So if you have a two-dimensional array of 3×4, then the total number of elements in this array = 3×4 = 12.

How do you find the length of a multidimensional array?

Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.

Can we use multi-dimensional arrays in Java?

No, Java does not support multi-dimensional arrays. Java supports arrays of arrays. In Java, a two-dimensional array is nothing but, an array of one-dimensional arrays.

How many dimensions can a multidimensional array have in Java?

The Java language does not limit the number of dimensions, but the Java VM spec limits the number of dimensions to 255.


2 Answers

There is no such thing as "length" for multi-dimensional array; it may not be rectangular. I'm guessing you're talking about the number of dimensions. You need to descend into it iteratively and count.

public int getDimensionCount(Object array) {
  int count = 0;
  Class arrayClass = array.getClass();
  while ( arrayClass.isArray() ) {
    count++;
    arrayClass = arrayClass.getComponentType();
  }
  return count;
}
like image 188
ChssPly76 Avatar answered Nov 15 '22 13:11

ChssPly76


Java arrays have lengths per instance, not all arrays in the same dimension have to have equals lengths. That said, you can get the lengths of instances in the.

Dimensions can be counted by the number of '[' in their name, this is quicker than descending the type hierarchy. The following code:

        int[][][] ary = {{{0},{1}}};

        Class cls = ary.getClass();

        boolean isAry = cls.isArray();
        String clsName = cls.getName();

        System.out.println("is array=" + isAry);
        System.out.println("name=" + clsName);

        int nrDims = 1 + clsName.lastIndexOf('[');

        System.out.println("nrDims=" + nrDims);

        Object orly = ary;

        for (int n = 0; n < nrDims; n++) {

            int len = Array.getLength(orly);

            System.out.println("dim[" + n + "]=" + len);

            if (0 < len) {
                orly = Array.get(orly, 0);
            }
        }

gives the following output:

is array=true
name=[[[I
nrDims=3
dim[0]=1
dim[1]=2
dim[2]=1
like image 22
rsp Avatar answered Nov 15 '22 15:11

rsp