Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
分配Java类的二维数组_Java_Arrays - Fatal编程技术网

分配Java类的二维数组

分配Java类的二维数组,java,arrays,Java,Arrays,这很好用 test [][] matrix = new test[5][]; for(int i =0 ; i < 5 ; i++) { matrix[i] = new test[5]; for(int j = 0 ; j< 5 ; j++) matrix[i][j] = new test(); } 这是有效的 int[][] matrix2 = new int[5][5]; 根本不

这很好用

test [][] matrix = new test[5][];

    for(int i =0 ; i < 5 ; i++)
        {
        matrix[i] = new test[5];
        for(int j = 0 ; j< 5 ; j++)
            matrix[i][j] = new test();
        }
这是有效的

int[][] matrix2 = new int[5][5];
根本不需要初始化


问题是为什么

因为您正在分配一个局部变量,而不是
矩阵的元素

for(test[] t: matrix) {
    t = new test[5]; // You are assiging to a local variable
    // t is a local variable!
}
更明显的是:

for(int i = 0; i < matrix.length; i++) {
    test[] t = matrix[i]; // t is obviously a local variable.

    // This will assign a new array to the local variable t:
    t = new test[5];

    // matrix[i] is still null, to prove it:
    System.out.println(matrix[i]); // Prints "null"
}
for(int i=0;i
因为您正在分配局部变量,而不是
矩阵的元素

for(test[] t: matrix) {
    t = new test[5]; // You are assiging to a local variable
    // t is a local variable!
}
更明显的是:

for(int i = 0; i < matrix.length; i++) {
    test[] t = matrix[i]; // t is obviously a local variable.

    // This will assign a new array to the local variable t:
    t = new test[5];

    // matrix[i] is still null, to prove it:
    System.out.println(matrix[i]); // Prints "null"
}
for(int i=0;i
这是:

  t = new test[5];
        for(test t2: t)
            t2 = new test();
将引用指定给数组中的元素,然后重新指定该引用以指向新的
test()
。您要做的是分配数组元素引用,例如

 test[2] = new test();
这:

将引用指定给数组中的元素,然后重新指定该引用以指向新的
test()
。您要做的是分配数组元素引用,例如

 test[2] = new test();

我认为两者都有效?有什么问题吗?你可以检查一下,第二个坏了。我想两个都行吗?有什么问题?你可以检查一下,第二个坏了。