Java set set to go heavy mechanism __java

Source: Internet
Author: User
Tags set set


About the collection in Java, we often use the set set does not have the characteristics of duplicate data, to carry out the weight of data, then the principle of how to weight it?


Recently interviewed a few people, during which there is talk to the collection of things, so by the way to ask this question, but are only know how to use,

Instead of looking at the principle of how the underlying code is going to go, it is possible that the underlying principles will be used to design some other scenario implementations.

So in this article, I want to be able to help some people:


The following is a class diagram of the Set collection:




Let's follow the process of execution:

1. First of all, we instantiate a set object

Set<8 large Basic type > set = new hashset<8 large basic type > ();
Set.add (8 major basic types);
The 2.add operation invokes the Add method in HashSet, which is implemented as follows:

Public boolean Add (E. e) {return
	map.put (E, PRESENT) ==null;
    }
the Add method in 3.HashSet relies on the HashMap put method, which is implemented as follows:

Public V-Put (K key, V value) {
        if (key = null) return
            Putfornullkey (value);
        int hash = hash (Key.hashcode ());
        int i = indexfor (hash, table.length);
        for (entry<k,v> e = table[i]; e!= null; e = e.next) {//each added, the loop is judged to be equal to the element in the map
            Object K;
            First determine if hashcode is consistent, and then judge whether the value is equal if
            (E.hash = = Hash && ((k = e.key) = = Key | | key.equals (k))) {
                V oldValue = E.value;
                E.value = value;
                E.recordaccess (this);
                Return OldValue
            }
        }

        modcount++;
        AddEntry (hash, key, value, I);
        return null;
    }

It is clear that the above operation 8 Basic types of data +string typeis useful, but if you want to apply a heavy approach to a complex object, the above approach is a bit less.

Knowing the sequence and principle of execution, you know how to implement it.

The following is the implementation of the rewrite object user, overriding the Equals and Hashcode methods.

Test class:

Package com.test.set;

Import Java.util.HashSet;
Import Java.util.Set;

public class Uniqueset {

    /**
     * 
     * * @param
     args
    /public static void main (string[] args) {

        User use R1 = new User (1, "a");
        User User2 = New User (2, "B");
        User User3 = New User (3, "C");
        User User4 = New User (2, "B");

        set<user> userset = new hashset<user> ();
        Userset.add (user1);
        Userset.add (user2);
        Userset.add (USER3);
        Userset.add (USER4);
        Enter the results id=1 username=a  id=2 username=b id=3 username=c for  
        (User u:userset) {
            System.out.println ( "Id=" + u.id + "" + "username=" + U.username);}}


Implementation class:

Package com.test.set; /** * Class Description: The set set filters out duplicate data for string types and 8 large underlying data types, * if you are storing other types of objects, you need to override the Hashcode method and the Equals method, * when the hashcode is equal (the Hashcode method is executed first), it
    To execute the Equals method, compare the value of each property * If consistent, then do not save in set, otherwise join set * * */public class User {//ID protected Integer ID;

    Name protected String username;
        Construct method public User (Integer ID, String username) {this.id = ID;
    This.username = Username;
        /** * If the object type is user, first compare hashcode, and then compare the value of each attribute/@Override public boolean equals (object obj) {
        if (obj = null) return false;
        if (this = = obj) return true;
            if (obj instanceof user) {User user = (user) obj; if (user.id = this.id) return true; Returns True if (User.ID = = This.id && user.username.equals (this.use) only compare ID//Compare values for each property to be consistent
        Rname)) return true;
    return false; /** * Overrides Hashcode method, returns the HASHCOde's different. Compares the value of each attribute/* @Override public int hashcode () {//return Id.hashcode ();
    return Id.hashcode () * Username.hashcode ();
 }
}



Above---------------------





Related Article

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.