Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing a 2d array in java

Tags:

java

arrays

I have been doing questions in my programming book and came across this question:

What is the output of the following code?

int[][] array = new int[5][6];
int[] x = {1, 2};
array[0] = x;
System.out.println("array[0][1] is " + array[0][1]);

The book says the answer is:

array[0][1] is 2

I learned so far that resizing an array isn't possible. From what I understand of this problem is that

int[][] array = new int[5][6]

is creating 5 arrays of 6 elements which would display 0's by default if you displayed it on the console

000000
000000
000000
000000
000000

and now from what I understand is that

array[0] = x;

is basically resizing the first array which has six elements of 0 into an array with 2 elements: 1 and 2.

What am I not understanding? Is it that

array[0] = x;

is making it so it's actually just changing the index 0 element and index 1 element of the first array? and keeping index 2,3,4,5 elements as 0's in array[0]?

I found this question Resize an Array while keeping current elements in Java? but I don't think it helps me answer this question.

like image 823
jakatak Avatar asked Jun 02 '15 16:06

jakatak


1 Answers

This line

array[0] = x;

is not resizing the array array[0]; it's replacing the array array[0] such that array is now

12
000000
000000
000000
000000

The old array[0] is now discarded and it will be garbage collected. Now array[0] and x refer to the same array object, {1, 2}.

like image 160
rgettman Avatar answered Oct 13 '22 14:10

rgettman