用Java获取数组维数
为了获得Java中的ArrayDimensions,我们将getClass(),isArray()和getComponentType()方法与决策结合起来使用迭代语句。
该getClass()方法方法返回运行时类的一个对象。该getClass()方法是java.lang.Object类的一部分。
声明-java.lang.Object.getClass()方法的声明如下-
public final Class getClass()
该isArray()方法检查传递的参数是否为数组。它返回一个布尔值,为true或false
语法 -该isArray()方法具有以下语法
Array.isArray(obj)
该getComponentType()方法返回表示数组的组件类型的Class。如果该类不是数组类,则此方法返回null。
声明-java.lang.Class.getComponentType()方法的声明如下-
public Class<?> getComponentType()
让我们看一个程序来获取Java中数组的维数-
示例
public class Example {
public static int dimensionOf(Object arr) {
int dimensionCount = 0;
Class c = arr.getClass(); // getting the runtime class of an object
while (c.isArray()) // check whether the object is an array {
c = c.getComponentType(); // returns the class denoting the component type of the array
dimensionCount++;
}
return dimensionCount;
}
public static void main(String args[]) {
String[][][] array = new String[7][9][8]; // creating a 3 dimensional String array
System.out.println(dimensionOf(array));
}
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短