Java Collection---Source code analysis of HashSet

Source: Internet
Author: User
Tags new set

First, HashSet Overview:

HashSet implements the set interface, which is supported by a hash table (actually a hashmap instance). It does not guarantee the set's iteration order, especially it does not guarantee that the order is constant. This class allows the use of NULL elements.

Second, the realization of HashSet:

For HashSet, it is based on the implementation of HashMap, hashset the underlying use HashMap to save all elements, so hashset implementation is relatively simple, related hashset operations, basically directly call the underlying HASHMAP related methods to complete,

The source code for HashSet is as follows:

1 Public classHashset<e>2Extends abstractset<e>3Implements Set<e>, cloneable, java.io.Serializable4{  5    StaticFinalLongSerialversionuid =-5024744406713321676L; 6  7    //the underlying uses HashMap to hold all the elements in the hashset. 8    PrivateTransient hashmap<e,object>map; 9      Ten    //defines a dummy object as the value of HashMap, which defines this object as static final.  One    Private StaticFinal Object PRESENT =NewObject ();  A   -    /** 14 * The default parameterless constructor constructs an empty hashset. 15 * 16 * The actual underlying will initialize an empty HashMap and use the default initial capacity of 16 and load factor 0.75. -*/   -     PublicHashSet () { +Map =NewHashmap<e,object>();  -    }   +   A    /** 23 * Constructs a new set containing the elements in the specified collection. 24 * 25 * The actual underlying uses the default load factor of 0.75 and is sufficient to contain the initial capacity of all elements in the specified * collection to create a hashmap. * @param c where the elements will be stored in the collection in this set. -*/   in     PublicHashSet (collection<? extends e>c) { -Map =NewHashmap<e,object> (Math.max (int) (C.size ()/.75f) +1, -));  toAddAll (c);  +    }   -   the    /** 35 * Constructs an empty hashset with the specified initialcapacity and loadfactor. 36 * 37 * The actual bottom layer constructs an empty hashmap with corresponding parameters. * @param initialcapacity initial capacity. Loadfactor * @param load factor. +*/   A     PublicHashSet (intInitialcapacity,floatloadfactor) {   theMap =NewHashmap<e,object>(initialcapacity, loadfactor);  +    }   -   $    /** 46 * Constructs an empty hashset with the specified initialcapacity. 47 * 48 * The actual bottom layer constructs an empty hashmap with corresponding parameters and loading factor loadfactor of 0.75. * @param initialcapacity initial capacity. -*/  Wuyi     PublicHashSet (intinitialcapacity) {   theMap =NewHashmap<e,object>(initialcapacity);  -    }   Wu   -    /** 56 * Constructs a new empty-link hash collection with the specified initialcapacity and loadfactor. 57 * This constructor is for package access, not public, and is actually just a support for linkedhashset. 58 * 59 * The actual underlying will construct an empty Linkedhashmap instance with the specified parameters. * @param initialcapacity initial capacity. Loadfactor * @param load factor. Dummy * @param mark. the*/   -HashSet (intInitialcapacity,floatLoadfactor, Boolean dummy) {   $Map =NewLinkedhashmap<e,object>(initialcapacity, loadfactor);  the    }   the   the    /** 69 * Returns an iterator that iterates over the elements in this set. The order of the returned elements is not specific. 70 * 71 * The bottom layer actually calls the keyset of the underlying HASHMAP to return all keys. 72 * The elements in the hashset are visible, just stored on the key of the underlying hashmap, and the * value uses a static final object identifier. The iterator * @return iterates over the elements in this set. the*/   the     PublicIterator<e>iterator () { the    returnMap.keyset (). iterator ();  +    }   -   the    /** 81 * Returns the number of elements in this set (capacity of Set). 82 * 83 * The lower layer actually calls HashMap's size () method to return the number of entry, and the number of elements in the set is obtained. * @return The number of elements in this set (capacity of Set). -*/   the     Public intsize () { the    returnmap.size ();  the    }   the   -    /** 91 * Returns True if this set contains no elements. 92 * 93 * The underlying actual call to HashMap's IsEmpty () determines whether the hashset is empty. 94 * @return Returns TRUE if this set contains no elements. the*/   the     PublicBoolean isEmpty () { the    returnMap.isempty (); 98    }   About   -    /** 101 * Returns True if this set contains the specified element. 102 * More specifically, returns True when and only if this set contains an e element that satisfies (O==null e==null:o.equals (E)) 103 *. 104 * 105 * The underlying actual call to HashMap ContainsKey determines whether the specified key is included. 106 * @param o There are elements in this set that have been tested. 107 * @return Returns TRUE if this set contains the specified element. 108*/  109     PublicBoolean contains (Object o) { the    returnMap.containskey (o); 111    }   the  113    /** 114 * If the specified element is not already contained in this set, the specified element is added. 115 * More specifically, if this set does not contain an element E2 that satisfies (E==null. E2==null:e.equals (E2)) 116 *, the specified element e is added to this set. 117 * If this set already contains the element, the call does not change the set and returns false. 118 * 119 * The bottom layer actually puts the element as key into the HashMap. 120 * Due to the HashMap put () method add Key-value pair, when the new put in HashMap entry key 121 * is the same as the set has entry (Hashcode () The return value is equal, by equals comparison also return TR UE), 122 * The value of the newly added entry will overwrite the value of the original entry, but there will be no change to key, 123 * Therefore if an existing element is added to HashSet, the newly added collection element will not be placed in HashMap, 1 24 * There is no change in the original element, which satisfies the feature that the element in set does not repeat. The * @param e is added to the element in this set. 126 * @return Returns TRUE if this set does not already contain the specified element. 127*/   -     PublicBoolean Add (E e) {129    returnMap.put (e, PRESENT) = =NULL;  the    }  131   the    /** 133 * If the specified element exists in this set, it is removed. 134 * More specifically, if this set contains an element e that satisfies (O==null e==null:o.equals (e)), 135 * removes it. Returns True 136 * If this set already contains the element (or True if this set changes because of a call). (Once the call returns, the set no longer contains the element). 137 * 138 * The lower layer actually calls HashMap's Remove method to delete the specified entry. 139 * @param o an object that needs to be removed if it exists in this set. $ * @return Returns TRUE if the set contains the specified element. 141*/  142     Publicboolean remove (Object o) {143    returnMap.Remove (o) = =PRESENT; 144    }  145  146    /** 147 * Removes all elements from this set. When this call returns, the set will be empty. 148 * 149 * The bottom layer actually calls HashMap's clear method to empty all elements in the entry. Max*/  151     Public voidClear () { themap.clear (); 153    }  154  155    /** 156 * Returns a shallow copy of this HashSet instance: The elements themselves are not copied. 157 * 158 * The underlying actually calls HashMap's Clone () method, gets the shallow copy of the HashMap, and sets it to HashSet. 159*/   the     PublicObject Clone () {161        Try {  162hashset<e> Newset = (hashset<e>) Super.clone (); 163Newset.map = (Hashmap<e, object>) Map.clone (); 164            returnNewset; 165}Catch(clonenotsupportedexception e) {166            Throw NewInternalerror (); 167        }  168    }  } 

Third, the relevant note:

For objects saved in HashSet, be aware that their equals and hashcode methods are correctly overridden to guarantee the uniqueness of the objects that are placed.

Java Collection---Source code analysis of HashSet

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.