Nominalista
Nominalista

Reputation: 4840

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?

Upvotes: 1

Views: 495

Answers (2)

SatyaTNV
SatyaTNV

Reputation: 4135

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.

Upvotes: 5

jsheeran
jsheeran

Reputation: 3037

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.

Upvotes: 6

Related Questions