用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 迎新祝福语简短20字
16 档案调动孩子祝福语简短
17 哥哥结婚的祝福语简短
18 送给姐姐简短的祝福语