![](/img/trans.png)
[英]How to cast a multidimensional array without knowing the dimension in Java
[英]How to get the length of any dimension of multidimensional array in Java?
JDK或流行的庫中是否有任何現成的實現?
我寫了以下函數:
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;
}
}
}
是正確和最佳的嗎?
看看java.util.Arrays
和java.lang.reflect.Array
。 它們具有可以為您提供幫助的功能。 至少您的方法可能會縮短。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.