简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM