问题:添加一个对象到集合中时,集合里面存放的是对象的引用还是对象本身?
答:对象的引用。以下代码可以证明:
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 }
输出结果:
SET VALUE FOR USERLIST2:
PRINT VALUE FOR USERLIST1
name
password
设置userList2中元素的value,但是userList1中元素的value也发生了改变,证明集合中存放的是对象的引用。