[英]Adding the same object to List in Java
Why when I add the same object to the list: 为什么当我将相同的对象添加到列表中时:
Integer a = new Integer(0);
testList.add(a);
a += 1;
testList.add(a);
The first didin't change? 第一个没有改变吗?
Because an Integer
is immutable. 因为
Integer
是不可变的。 When you modify the value of the one referenced by a
, you're creating a new object and updating the reference to it. 修改
a
引用的值时,您将创建一个新对象并更新对该对象的引用。 testList
holds a reference to both objects. testList
包含对两个对象的引用。
Since Integer
wrapper class is immutable in java. 由于
Integer
包装器类在Java中是不可变的。 Not only Integer
, all wrapper classes and String
is immutable. 不仅
Integer
,所有包装器类和String
都是不可变的。
a
is a reference which points to an object. a
是指向对象的参考。 When you run a += 1
, that reassigns a
to reference a new Integer object, with a different value. 当您运行
a += 1
,它将重新分配a
来引用具有不同值的新Integer对象。
You never modified the original object. 您从未修改原始对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.