This is working just fine.
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();
}
This is not working
for(test[] t: matrix)
{
t = new test[5];
for(test t2: t)
t2 = new test();
}
This is working
int[][] matrix2 = new int[5][5];
without to initialize at all
The question is why ?
Because you are assiging to a local variable and not to an element of matrix
.
for(test[] t: matrix) {
t = new test[5]; // You are assiging to a local variable
// t is a local variable!
}
To make it more obvious:
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"
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments