java - Why do original variables change when new variables are changed? -
i have following block of code:
arraylist<integer> list1 = new arraylist<integer>(); arraylist<integer> list2 = list1; // both list1 , list2 empty arraylists system.out.println(list1.size()); // prints: 0 list2.add(7); system.out.println(list1.size()); // prints: 1
how come when modify list2, list1 modified? causing concurrentmodificationexception
s in program. how can edit list2 without changing list1?
list1
, list2
2 different references set refer same object.
if want 2 different lists same contents, can make copy:
arraylist<integer> list1 = new arraylist<integer>(); arraylist<integer> list2 = new arraylist<integer>(list1);
Comments
Post a Comment