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?
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. When you modify the value of the one referenced by a
, you're creating a new object and updating the reference to it. testList
holds a reference to both objects.
Since Integer
wrapper class is immutable in java. Not only Integer
, all wrapper classes and String
is immutable.
a
is a reference which points to an object. When you run a += 1
, that reassigns a
to reference a new Integer object, with a different value.
You never modified the original object.
Integer
in this case, return a new Object
Sep 29, 2015 at 12:27
MyClass
, and sure, it can be mutable if you want, but you can't overload the +=
operator for it.
Sep 29, 2015 at 12:31