assigning two arrays equal to each other problems

  • A+
Category:Languages
public static void main(String[]args) {       int[] x = {1, 2, 3, 4};     int[] y ;     y = x;     x[1] = 11;     x = new int[2];      x[0]=99;     for (int i = 0; i < y.length; i++)       System.out.print(y[i] + " ");     System.out.println("");     for (int i = 0; i < x.length; i++)           System.out.print(x[i] + " "); } 

answer is

1 11 3 4  99 0 

My question is I thought when you assign two arrays, they share the same changes since they are objects... like when I set x[1] = 11; it changed the value of y, so shouldn't y still be identical to x after changing it to a 2-sized array, or since I am changing the size they no longer point to the same address?

 


int[] x = {1, 2, 3, 4}; 

{1, 2, 3, 4} is allocated as an array. A reference to it is assigned to x.

int[] y ; y = x; 

A reference to that same array is assigned to y as well.

x[1] = 11; 

The array that both x and y refer to is now {1, 11, 3, 4}.

x = new int[2]; 

A new array is allocated, due to Java semantics, as {0, 0}. A reference to it is assigned to x. Now x and y refer to two different arrays. There is no resizing being done.

x[0]=99; 

The array referred to by x is changed, and now contains {99, 0}. This has nothing to do with the array y refers to, which is still happily {1, 11, 3, 4}.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: