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

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -