How do I find the length of a multi-dimensional array with reflection on 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.
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.
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.
The Java language does not limit the number of dimensions, but the Java VM spec limits the number of dimensions to 255.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With