Java Collection---Source code analysis of HashSet

Source: Internet
Author: User
Tags new set shallow copy

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>2    extendsAbstractset<e>3    ImplementsSet<e&gt, Cloneable, java.io.Serializable44{5    Static Final LongSerialversionuid = -5024744406713321676l;6 7    //Bottom use HashMap to save all elements in the hashset. 8    Private transientHashmap<e,object> map;9 Ten    //Define a dummy object as the value of HashMap and define this object as static final.  One    Private Static FinalObject PRESENT =NewObject (); A  -    /**  * The default parameterless constructor constructs an empty hashset.  The actual  underlying layer Initializes an empty HashMap and uses the default initial capacity of 16 and load factor 0.75. *   / -     PublicHashSet () { +Map =NewHashmap<e,object> (); -} +  A    /**  * Constructs a new set that contains the elements in the specified collection. The actual  underlying base 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<?extendsE> c) { -Map =NewHashmap<e,object> (Math.max (int) (C.size ()/.75f) + 1, 16)); toAddAll (c); +} -  the    /**  * Constructs an empty hashset with the specified initialcapacity and loadfactor.  * PNS * 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); +} -  $    /**  * Constructs an empty hashset with the specified initialcapacity.  the actual  bottom layer constructs an empty hashmap with corresponding parameters and load factor loadfactor of 0.75.  * @param initialcapacity initial capacity. *   /Wuyi     PublicHashSet (intinitialcapacity) { theMap =NewHashmap<e,object> (initialcapacity); -} Wu  -    /**  * Constructs a new empty-link hash collection with the specified initialcapacity and loadfactor.  * This constructor is for package access, not public, and is actually just a support for linkedhashset.  * *  * * The actual underlying will construct an empty Linkedhashmap instance with the specified parameters.  * @param initialcapacity initial capacity.  loadfactor * @param load factor.  Dummy * @param mark. * *   -HashSet (intInitialcapacity,floatLoadfactor,BooleanDummy) { $Map =NewLinkedhashmap<e,object> (initialcapacity, loadfactor); the} the  the    /**  * Returns an iterator that iterates over the elements in this set. The order of the returned elements is not specific.  The bottom  layer actually calls the keyset of the underlying HASHMAP to return all keys.  The elements in the hashset are visible only on the underlying HashMap key, and the * value  uses a static final object identifier.  The iterator * @return iterates over the elements in this set. * *   the     PublicIterator<e> Iterator () { the    returnMap.keyset (). iterator (); +} -  the    /** Bayi * Returns the number of elements in this set (capacity of Set).  * *  * * * The bottom of the actual call to HashMap's size () method returns 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  -    /**  * If this set does not contain any elements, it returns true.  the HashMap  () IsEmpty () is actually called by the bottom layer to determine whether the hashset is empty. 94 * @return Returns True if this set contains no elements. *   the     Public BooleanIsEmpty () { 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 * * * * * 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     Public BooleanContains (Object o) { the    returnMap.containskey (o);111} the 113    /** the* If the specified element is not already contained in this set, the specified element is added. the* More specifically, if this set does not contain the content (E==null? E2==null:e.equals (E2)) the* element E2, 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 underlying actually puts the element as key into the HashMap. -* Because the put () method of HashMap adds Key-value pair, when the new is placed in the entry of HashMap key121* Same as key with entry in the Set (Hashcode () return value is equal, also return true by equals),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 the HashMap,124* The original element will not have any changes, 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*/ -     Public BooleanAdd (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 true136 * 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     Public BooleanRemove (Object o) {143    returnMap.Remove (o) ==present;144}145 146    /**147 * Remove all elements from this set. When this call returns, the set will be empty. 148 *149 * The lower layer actually calls HashMap's clear method to empty all elements in the entry. * *  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 actual call to HashMap's Clone () method, gets the shallow copy of 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}169}


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.