MrSebo
MrSebo

Reputation: 49

Java multidimensional array layout

I am studying for an exam and this is about memory allocation of a multidimensional java array.

Given is the following code:

double [][] a = new double[4][];
for (int i = 0; i < 4; i++)
     a[i] = new double[4-i];

I am supposed to draw the memory layout of this array, but I am afraid I don't fully comprehend how it even works.

It would also be very kind of you if you could show me how to print this array as list to the console so I can look at it. :)

Thank you for your time.

Upvotes: 0

Views: 208

Answers (3)

Anshul Singhal
Anshul Singhal

Reputation: 2201

Array memory layout

I am not sure if this answers your question.

Above picture depicts how array elements will be stored in memory.

Upvotes: 1

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

Since your array a is an array of array (2D) , you can use enhanced for loop to print elements.

So, your outer loop has double[] as type, and hence that declaration. If you iterate through your a in one more inner loop, you will get the type double.

     double[][] a = {
        {1, 3}, 
        {4, 5}, 
        {7, 8}
    };
List<Double> dou = new ArrayList<Double>();

for (double[] k: a) {
    for (double element: k) {
        dou.add(element) ;
    }

}
System.out.println(dou);

Output

[1.0, 3.0, 4.0, 5.0, 7.0, 8.0]

Upvotes: 1

Ruslan
Ruslan

Reputation: 6290

you don't have to create new array in the for loop. Try this:

    double[][] a = new double[4][3];

Or you can initialize it in one statement like:

    double[][] a = {
        {1, 3, 2}, 
        {4, 5, 6}, 
        {7, 8, 9}
    };

And then print:

    System.out.println(Arrays.deepToString(a))

Upvotes: 3

Related Questions