Allocating 2 dimension array of a class Java

USer22999299

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 ?

icza

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Allocating an array of a class c++

From Dev

Allocating an array of a class c++

From Dev

Java passing 2 dimension array to method

From Dev

Java passing 2 dimension array to method

From Dev

Allocating a 2d Array

From Dev

How to create a 2-dimension array for abstract class

From Dev

Upgrade 1 dimension array to 2 dimension array

From Dev

Two dimension java array

From Dev

How to split string from 3 dimension array to new 2 dimension array in java

From Dev

length in 2 dimension array

From Dev

Dynamically allocating a 2D array in C

From Dev

Memory management in allocating 2-D array

From Dev

Dynamically allocating a 2D string array

From Dev

Allocating memory for a 2-dimensional array that is in a structure

From Dev

Allocating a 2-dimensional structure array with malloc

From Dev

Memory management in allocating 2-D array

From Dev

Allocating 2D array dynamically

From Dev

2 dimension array processing in haskell

From Dev

2 dimension array is not looping in laravel

From Dev

how to count in 2 dimension array

From Dev

Java 2 dim array class

From Dev

Forward Declaring and Dynamically Allocating an Array of Pointers of that Declared Class?

From Dev

Allocating array of objects inside another class (C++)

From Dev

passing two dimension array to class member function

From Dev

Allocating 2D array with pointer to fixed-size array

From Dev

2 dimension array to multiple 1 dimension arrays with keys

From Dev

c: issues when allocating 2d char array dynamically?

From Dev

C segmentation fault when dynamically allocating 2d array

From Dev

Allocating a 2D contiguous array within a function

Related Related

HotTag

Archive