问题描述
在这个例子中,
int x = 5;
int y = x;
x = 4;
y将保持为5,因为x正在被重新分配,并且它不会操纵它用于引用的对象无论如何。我的问题是,我刚刚说了一个正确的思考方式吗?或者是否存在x中存储的重复内存,并且重复放在y中。
y will remain 5 because x is just being reassigned and it is not manipulating the object it used to refer to in anyway. My question is, is what I just said a correct way of thinking about it? Or is there a duplication of the memory stored in 'x' and that duplication is put in 'y'.
推荐答案
与对象不同,基元直接存储在变量中。也就是说,基本类型的变量不存储对基元的引用,它直接存储基元的值。
Primitives, unlike objects, are stored directly inside the variable. That is, a variable of primitive type is not storing a reference to a primitive, it stores the primitive's value directly.
当一个基元变量被分配给另一个基元变量时,它会复制价值。
When one primitive variable is assigned to another primitive variable, it copies the value.
当你这么做时
int x = 5;
int y = x;
x = 4;
x
将其中的值设置为4, y
仍然具有值5,因为它的值是独立的。
x
sets the value inside of it to 4, and y
still has the value 5 because its value is separate.
一个变量的唯一方法是通过改变另一个变量来改变,如果两个变量都是对可变对象的引用,并且对象是变异的 - 因为它们都在查看相同的对象,而不是它们自己的副本,它们都观察到相同的变化。 (注意,例如,字符串是不可变的,永远不会突然改变,但数组和集合可以)
The only way for one variable to be changed by a change to another variable, is if both variables are references to a 'mutable' object, and the object is mutated - since they both are looking at the same object, rather than their own copies, they both observe the same change. (Note for example that strings, being immutable, will never 'suddenly change', but arrays and collections can)
这篇关于正确的原始任务思维方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!