简体   繁体   English

更改已设置相等的对象

[英]Altering objects that have been set equal

I'm setting an array equal to another array. 我正在设置一个等于另一个数组的数组。

So let's say array B = array C. 所以我们假设数组B =数组C.

Then, if I do operations on array B, changing it's values, does C also change? 然后,如果我对数组B进行操作,更改它的值,C是否也会改变?

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. 就像在您的示例数组B = array C中一样.B将保存对数组C的引用。因此数组B中的任何更改都将反映在数组C中。

Yes, they are changed. 是的,他们被改变了。

The array is an object, so you assign only the reference, after assignment "array B = array C." 数组是一个对象,因此在赋值“array B = array C”之后,只分配引用。 both variables would hold the same reference. 两个变量都将保持相同的参考。 As a result you will have one object and two references 因此,您将拥有一个对象和两个引用

UPDATE UPDATE

For "real copy" you need to use System.arraycopy() or Arrays.copyOf() 对于“真实副本”,您需要使用System.arraycopy()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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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