Does the JAVA set store objects or object references ?, Java Collection
Q: when an object is added to a set, does the set store the object reference or the object itself?
A: References an object. The following code proves that:
1 import JAVA.util.ArrayList; 2 import JAVA.util.List; 3 4 public class Test5 { 5 public static void main(String args[]){ 6 List<User> userList1 = new ArrayList<User>(); 7 List<User> userList2 = new ArrayList<User>(); 8 User user1 = new User(); 9 userList1.add(user1); 10 userList2.add(user1);11 12 System.out.println("SET VALUE FOR USERLIST2:"); 13 for(User user: userList2){14 user.setName("name");15 user.setPassword("password"); 16 }17 System.out.println("PRINT VALUE FOR USERLIST1:");18 for(User user: userList1){19 System.out.println(user.getName()); 20 System.out.println(user.getPassword()); 21 } 22 }23 24 public static class User{25 private String name;26 private String password;27 28 public String getName() {29 return name;30 }31 public void setName(String name) {32 this.name = name;33 }34 public String getPassword() {35 return password;36 }37 public void setPassword(String password) {38 this.password = password;39 }40 }41 }
Output result:
Set value for USERLIST2:
Print value for USERLIST1
Name
Password
Set the value of the element in userList2, but the value of the element in userList1 has also changed, proving that the object is referenced in the set.
From: http://bettereveryday.iteye.com/blog/682322