简体   繁体   中英

Why do original variables change when new variables are changed?

I have the following block of code:

ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = list1;
// both list1 and list2 are empty arraylists
System.out.println(list1.size()); // prints: 0
list2.add(7);
System.out.println(list1.size()); // prints: 1

How come when I modify list2, list1 is also modified? This is causing ConcurrentModificationException s in my program. How can I edit list2 without changing list1?

list1 and list2 are two different references that you set to refer to the same object.

If you want two different lists with the same contents, you can make a copy:

ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>(list1);

In the Java programming language, the value of variables is only stored for primitive types. For Object (and other classes) the values stored are the reference to the actual object.

In your example, you are just creating a variable list2 whose reference points to the object list1, so it is a different variable but with the same reference value and which points to the same object. This is why when you add an element to the list1, list2 is also affected (it is actually the same list. Just a duplicate reference to it).

In order for you to change this behavior, you need to make list2 be equal to a new ArrayList(), either making it an empty new ArrayList or using the copy-constructor and passing list1 as an argument.

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