1

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?

Nominalista
  • 4,632
  • 11
  • 43
  • 102
  • In the future, include all your relevant code when asking questions such as this. As shown, this is not even close to being valid Java. Also, read up on "Immutable" types (such as Integer). – JoeG Sep 29 '15 at 12:48

2 Answers2

6

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.

jsheeran
  • 2,912
  • 2
  • 17
  • 32
5

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.

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31