Is there any ready implementations in JDK or popular libraries?
I wrote the following function:
public static int length(Object array, int level) {
if( level < 0 ) {
throw new IllegalArgumentException();
}
else if( level == 0 ) {
if( !array.getClass().isArray() ) {
throw new IndexOutOfBoundsException();
}
else {
return Array.getLength(array);
}
}
else {
if( !array.getClass().isArray() ) {
throw new IndexOutOfBoundsException();
}
else {
int length = Array.getLength(array);
int nextlength, maxnextlength = 0;
Object element;
for(int i=0; i<length; ++i) {
element = Array.get(array, i);
if( element != null ) {
nextlength = Array.getLength(element);
if( nextlength > maxnextlength ) {
maxnextlength = nextlength;
}
}
}
return maxnextlength;
}
}
}
is it correct and optimal?
Take a look on java.util.Arrays
and java.lang.reflect.Array
. They have functions that can help you. At least your method may be shorten.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.