获取 Java 中数组的维度
为了获得 Java 中的数组维度,我们结合决策制定和迭代语句使用了 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));
}
}
广告
数据结构
网络工程
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP