Does the JAVA set store objects or object references ?, Java Collection

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.