Resize 2d array in java

I asked 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 found out that resizing an array is not possible. From what I understand, the problem is that

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

creates 5 arrays of 6 elements that would display 0 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; 

basically resizes the first array, which has six elements from 0 to an array with two elements: 1 and 2.

What? I do not understand? This is what

 array[0] = x; 

does it so that it really just changes the index 0 element and the index 1 element of the first array? and saving the index of 2,3,4,5 elements as 0 in the array [0]?

I found this question Resize array while saving current elements in Java? but I don’t think it helps me answer this question.

+5
source share
2 answers

This line

 array[0] = x; 

does not change the size of the array array[0] ; it replaces the array array[0] so that array now

 12 000000 000000 000000 000000 

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

+10
source
 array[0]=x 

This line does not resize the array. Makes array [0] and x a reference to the same object. To make your concept more clear, I would include a snippet

  int[][] array = new int[5][6]; System.out.println("Initial length"); for(int i=0;i<array.length;i++) System.out.println("length of array["+i+"] is " +array[i].length); int[] x = {1, 2}; array[0] = x;//This line makes array[0] and x to refer to the same object System.out.println("After changes made"); for(int i=0;i<array.length;i++) System.out.println("length of array["+i+"] is " +array[i].length); System.out.println("array[0][1]= "+array[0][1]); //changing the content of object referred by x x[0]=3; x[1]=6; System.out.println("After changing X"); System.out.println("array[0][0]= "+array[0][0]+" array[0][1]="+array[0][1]); 

Output

 Initial length length of array[0] is 6 length of array[1] is 6 length of array[2] is 6 length of array[3] is 6 length of array[4] is 6 After changes made length of array[0] is 2 length of array[1] is 6 length of array[2] is 6 length of array[3] is 6 length of array[4] is 6 array[0][1]= 2 After changing content of object referred by x array[0][0]= 3 array[0][1]=6 

So, you can notice that after array[0]=x , if you change the contents of the object passed to x, the changes will be observed both in the array of arrays [0] and in x, because they refer to the same object . Hope this helps you. Excellent coding!

+1
source

All Articles