分配类Java的2维数组

时间:2014-07-25 13:33:03

标签: 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();
        }

这不起作用

for(test[] t: matrix)
        {
        t = new test[5];
        for(test t2: t)
            t2 = new test();
        }

这是有效的

int[][] matrix2 = new int[5][5];

根本没有初始化

问题是为什么?

2 个答案:

答案 0 :(得分:3)

因为您要分配给本地变量而不是matrix的元素。

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"
}

答案 1 :(得分:1)

此:

  t = new test[5];
        for(test t2: t)
            t2 = new test();

为数组中的元素分配引用,然后重新分配该引用指向新的test()。你想要做的是分配数组元素引用,例如。

 test[2] = new test();