简体   繁体   中英

Altering objects that have been set equal

I'm setting an array equal to another array.

So let's say array B = array C.

Then, if I do operations on array B, changing it's values, does C also change?

I want to say absolutely not, but I'm having a brain fart and I feel like that what's happening in my code right now.

When you assign one array to another array the array will hold the reference so if you change the value in one array then it will surely change the value of other.

like in your example array B = array C. B will hold the reference to array C. so any changes in array B will reflect in array C.

Yes, they are changed.

The array is an object, so you assign only the reference, after assignment "array B = array C." both variables would hold the same reference. As a result you will have one object and two references

UPDATE

For "real copy" you need to use System.arraycopy() or Arrays.copyOf()

int[] arrayC = {1,2,3,4,5,6,7,8,9,10};
int[] arrayB = new int[arrayC.length];
System.arraycopy(arrayC, 0, arrayB, 0, arrayC.length );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM