使用 Java 反射方法创建一个二维数组的新实例
可以使用 java.lang.reflect.Array.newInstance() 方法创建二维数组的新实例。此方法基本上创建具有所需的组件类型和长度的二维数组。
演示使用 Array.newInstance() 方法创建二维数组的程序如下 -
示例
import java.lang.reflect.Array;
public class Demo {
public static void main (String args[]) {
int size[] = {3, 3};
int arr[][] = (int[][])Array.newInstance(int.class, size);
System.out.println("The two-dimensional array is:");
for(int[] i: arr) {
for(int j: i ) {
System.out.print(j + " ");
}
System.out.println();
}
}
}输出
The two-dimensional array is: 0 0 0 0 0 0 0 0 0
现在让我们了解上述程序。使用 Array.newInstance() 方法创建二维数组的新实例。演示这一点的代码片段如下 -
int size[] = {3, 3};
int arr[][] = (int[][])Array.newInstance(int.class, size);然后使用嵌套 for 循环显示数组元素。演示这一点的代码片段如下 -
System.out.println("The two-dimensional array is:");
for(int[] i: arr) {
for(int j: i ) {
System.out.print(j + " ");
}
System.out.println();
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP