Pergunta

I have this code:

int[] copyFrom = {1,2,3,4,5,6,7,8,9};
int[] copyTo   = new int[9];
copyTo = copyFrom;
copyFrom = new int[9];
System.out.println(copyTo[0]);

The value I get is "1"..

To my understanding copyTo=copyFrom copies just the reference to the array. So why when I initialize copyFrom, copyTo still refers to the old memory?

Apologies if this is dumb or duplicate, I am a novice user.

Foi útil?

Solução

Here is what is happening:

int[] copyFrom = {1,2,3,4,5,6,7,8,9};
int[] copyTo   = new int[9];

can be visualized as

copyFrom ------------> [1,2,3,4,5,6,7,8,9]

copyTo   ------------> [0,0,0,0,0,0,0,0,0]

Now copyTo = copyFrom; makes copyTo hold same value as copyFrom so new situation looks like

copyFrom ---------+
                  |
                  +--> [1,2,3,4,5,6,7,8,9]
                  |
copyTo   ---------+ 

As you see there are still two references, but they just hold same value so changing one of them can't affect other (I am talking about changing value of references - ref = new Value(); - not state of object they hold ref.setParam(foo);)

Then you change copyFrom reference to hold new array copyFrom = new int[9]; so now you have

copyFrom ------------> [0,0,0,0,0,0,0,0,0]

copyTo   ------------> [1,2,3,4,5,6,7,8,9]

That is why System.out.println(copyTo[0]); prints 1.

Outras dicas

let's put in this way:

int[] copyFrom = {1,2,3,4,5,6,7,8,9}; //cpFrom holds memory addr 123 to the array
int[] copyTo   = new int[9]; //cpTo holds addr 456 to a new array
copyTo = copyFrom; //now cpTo and cpFrom hold same addr 123
copyFrom = new int[9]; //now cpFrom holds addr 789(new arr), but cpTo still holds 123

now you see

1- copyFrom -> array1 = {1,2..9}
2- copyTo -> array2 = new int[]
3- copyTo -> array1 (array2 is lost)
3- copyFrom -> array3 = new int[]

So in the end, copyTo points to the first array, hence the answer.

You copy the reference to a memory location containing the data {1,2,3,4,5,6,7,8,9}. Then when you initializes copyFrom, it refers to a new memory location, while copyTo still refers to the first memory location.

When you do copyTo = copyFrom; in 3rd line. copyTo points to the array at line 1 i.e copyFrom. and in next line you are pointing copyFrom to a new array.copyTo array still points to array at line 1 and when you print copyTo[0] ,it picks the first element of the array it is pointing to. Hence the answer 1.

Hope it clarifies.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top