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?

1
  • 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
    Commented Sep 29, 2015 at 12:48

2 Answers 2

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.

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.

9
  • What about class that I create ? Should change? Commented Sep 29, 2015 at 12:27
  • @Nominalista immutable means every change done to the Object, Integer in this case, return a new Object Commented Sep 29, 2015 at 12:27
  • 1
    @Nominalista you can create MyClass, and sure, it can be mutable if you want, but you can't overload the += operator for it. Commented Sep 29, 2015 at 12:31
  • 1
    The new class is mutable if you have a method that updates its internal state. Commented Sep 29, 2015 at 12:34
  • 1
    @Nominalista check this for immutable Commented Sep 29, 2015 at 12:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.