Java Collection source code analysis (5) HashSet & lt; E & gt;, javahashset

Source: Internet
Author: User

Java Collection source code analysis (5) HashSet <E>, javahashset
Introduction to HashSet

HashSet implements the Set interface, which is supported by a hash table (actually a HashMap instance. It does not guarantee the set iteration sequence; in particular, it does not ensure that the sequence remains unchanged. This class allows the use of null elements.

HashSet source code analysis

For a HashSet, it is implemented based on HashMap. The HashSet uses HashMap to store all elements at the underlying layer. Therefore, the implementation of HashSet is simple and related HashSet operations, basically, it is done by directly calling the related methods of the underlying HashMap,
The source code of HashSet is as follows:

/** @ (#) HashSet. java1.37 06/04/21 ** Copyright 2006 Sun Microsystems, Inc. all rights reserved. * sun proprietary/CONFIDENTIAL. use is subject to license terms. */package java. util;/*** @ param <E> the type of elements maintained by this set *** @ author Josh Bloch * @ author Neal Gafter * @ version 1.37, 04/21/06 * @ see Collection * @ see Set * @ see TreeSet * @ see HashMap * @ since 1.2 */public class HashSet <E> extends AbstractSet <E> implements Set <E>, Cloneable, java. io. serializable {static final long serialVersionUID =-5024744406713321676L; // use HashMap to save all elements in the HashSet. Private transient HashMap <E, Object> map; // defines a virtual Object as the value of HashMap, which is defined as static final. Private static final Object PRESENT = new Object (); // The default no-argument constructor constructs an empty HashSet. An empty HashMap is initialized at the underlying layer. Public HashSet () {map = new HashMap <E, Object> () ;}// construct a new set containing the elements in the specified collection. // The actual underlying layer uses the imported Collection divided by 0.75 plus a HashMap of 1 or a HashMap of 16 size. The maximum public HashSet (Collection <? Extends E> c) {map = new HashMap <E, Object> (Math. max (int) (c. size ()/. 75f) + 1, 16); addAll (c) ;}/ *** construct an empty HashSet with the specified initialCapacity and loadFactor. * The actual underlying layer constructs an empty HashMap with corresponding parameters. ** @ Param initialCapacity * initial capacity * @ param loadFactor * loading Factor */public HashSet (int initialCapacity, float loadFactor) {map = new HashMap <E, Object> (initialCapacity, loadFactor);}/*** construct an empty HashSet with the specified initialCapacity. * The actual underlying layer constructs an empty HashMap with corresponding parameters. * @ Param initialCapacity * initial capacity */public HashSet (int initialCapacity) {map = new HashMap <E, Object> (initialCapacity );} /*** construct a new empty link hash set with the specified initialCapacity and loadFactor. * This constructor is the package access permission and is not disclosed to the public. It is actually only supported by javashashset. ** At the underlying layer, an empty LinkedHashMap instance is constructed with the specified parameters. * @ Param initialCapacity * initial capacity * @ param loadFactor * loading Factor * @ param dummy * mark */HashSet (int initialCapacity, float loadFactor, boolean dummy) {map = new LinkedHashMap <E, Object> (initialCapacity, loadFactor);}/*** returns the iterator for iteration of the elements in this set. The returned element sequence is not specific. ** The underlying layer actually calls the keySet of the underlying HashMap to return all keys. * The elements in the HashSet are only stored on the key of the underlying HashMap. * value uses a static final Object identifier. * @ Return Iterator that iterates on the elements in this set. */Public Iterator <E> iterator () {return map. keySet (). iterator () ;}// return the number of elements in the set (set capacity ). // The number of entries returned by actually calling the size () method of HashMap at the underlying layer will be the number of elements in the Set. Public int size () {return map. size () ;}// returns true if this set does not contain any element. // The isEmpty () of the HashMap actually called at the underlying layer to determine whether the HashSet is empty. Public boolean isEmpty () {return map. isEmpty () ;}// if this set contains the specified element, true is returned. // More accurately, when and only when this set contains a satisfied (o = null? E = null: o. equals (e), returns true. Public boolean contains (Object o) {return map. containsKey (o) ;}// if this set does not contain the specified element, add the specified element. // To be more precise, if this set does not contain meet (e = null? E2 = null: e. equals (e2) element e2, then add the specified Element e to this set. // If this set already contains this element, the call does not change the set and returns false. // The underlying layer actually puts this element as a key into HashMap. // When a key-value pair is added to the put () method of HashMap, when the key in the newly added HashMap Entry is the same as the key of the original Entry in the Set (hashCode () returns the same value, returns true through equals comparison), // The value of the newly added Entry will overwrite the value of the original Entry, but the key will not change, // if an existing element is added to a HashSet, the newly added collection element will not be put into the HashMap, and the original element will not change, this satisfies the non-repetition of elements in the Set. Public boolean add (E e) {return map. put (e, PRESENT) = null;} // if the specified element exists in this set, remove it. // More accurately, if this set contains a condition (o = null? E = null: o. equals (e) Element e, // remove it. If this set already contains this element, true // is returned (or, if this set is changed due to call, true is returned ). (This set no longer contains this element once it is returned ). Public boolean remove (Object o) {return map. remove (o) = PRESENT;} // remove all elements from this set. After this call is returned, the set is empty. Public void clear () {map. clear () ;}// returns a superficial copy of this HashSet instance: these elements are not copied. // The underlying layer actually calls the clone () method of HashMap to obtain the superficial copy of HashMap and set it to HashSet. Public Object clone () {try {HashSet <E> newSet = (HashSet <E>) super. clone (); newSet. map = (HashMap <E, Object>) map. clone (); return newSet;} catch (CloneNotSupportedException e) {throw new InternalError () ;}// java. io. the Write function of Serializable is private void writeObject (java. io. objectOutputStream s) throws java. io. IOException {// Write out any hidden serialization magics. defaultWriteObject (); // Write out HashMap capacity and load factor s. writeInt (map. capacity (); s. writeFloat (map. loadFactor (); // Write out size s. writeInt (map. size (); // Write out all elements in the proper order. for (Iterator I = map. keySet (). iterator (); I. hasNext ();) s. writeObject (I. next ();} // java. io. serializable's read function private void readObject (java. io. objectInputStream s) throws java. io. IOException, ClassNotFoundException {// Read in any hidden serialization magics. defaultReadObject (); // Read in HashMap capacity and load factor and create backing HashMap int capacity = s. readInt (); float loadFactor = s. readFloat (); map = (HashSet) this) instanceof role HashSet? New LinkedHashMap <E, Object> (capacity, loadFactor): new HashMap <E, Object> (capacity, loadFactor); // Read in size int size = s. readInt (); // Read in all elements in the proper order. for (int I = 0; I <size; I ++) {E e = (E) s. readObject (); map. put (e, PRESENT );}}}

  

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.