Java-hashset Source

Source: Internet
Author: User
Tags shallow copy

 PackageJava.util;Importjava.io.InvalidObjectException;/*** HashSet inherits the Abstractset class, implements the set interface, supported by the hash table (actually a hashmap instance). HashSet does not guarantee the traversal order of the * set in this class, nor does it guarantee the permanent invariant of the data order in the set. HashSet allows null values to be stored, if there is a null value, there is only one. * Note that HashSet does not implement synchronization, which is not thread-safe, if multiple threads access a hash collection at the same time, and at least one thread is modified, the * must be synchronized externally, usually by performing a synchronous operation on the object that encapsulates the set naturally. If such an object does not exist, you should use the Collections.synchronizedset method to encapsulate the set. It is a good idea to do this at creation time to prevent accidental, out-of-sync access to the set: * Set S = Collections.synchronizedset (new HashSet (...)); * <p> * Note the remove operation of the hash set, concurrentmodificationexception exception may occur if the delete operation occurs during traversal; Try to use HashSet's own iterator for deletion, i.e. iterator; in the case of concurrent modification, the iterator will fail quickly;*/ Public classHashset<e>extendsAbstractset<e>ImplementsSet<e>, cloneable, java.io.serializable{Static Final LongSerialversionuid = -5024744406713321676l; //The bottom of the hashset is implemented by HashMap, and the HashMap field is of type transient and cannot be serialized    Private transientHashmap<e,object>map; /*** The value defined for this hashmap is a dummy value that cannot be modified statically because hashset only needs to use key, and HashMap is the Key-value key value pair. Therefore, when you add a key-value pair to a map, the value of the key-value pair is fixed as present 
    */    Private Static FinalObject PRESENT =NewObject (); /*** Default constructor, the initial capacity of the underlying initialization of a hashmap,hashmap is 16, and the load factor is 0.75*/     PublicHashSet () {map=NewHashmap<>(); }  /*** Set converted to HashSet's constructor, divided into two steps: * * 1. Return (C.size ()/.75f) + 1 and 162 larger numbers, why? * Because the default initial capacity of HashMap is 16, and the load factor is when 0.75,hashmap will be expanded, is when the threshold value of HashMap * (initial capacity * load factor) is greater than hashmap actual size, HashMap will be expanded, so ( C.size ()/.75f) +1 is the actual size; * 2. Add all elements of the collection C to hashset; * If parameter c is null, a null pointer exception will be thrown;*/     PublicHashSet (collection<?extendsE>c) {map=NewHashmap<> (Math.max (int) (C.size ()/.75f) + 1, 16));    AddAll (c); }   /*** Constructs a hashmap of the specified capacity and load factor, * throws a IllegalArgumentException exception if the initial capacity or load factor is less than 0*/     PublicHashSet (intInitialcapacity,floatloadfactor) {Map=NewHashmap<>(initialcapacity, loadfactor); }    /*** Constructs a hashmap of a specified capacity, the default load factor is 0.75 * IllegalArgumentException exception is thrown if the initial capacity is less than 0*/     PublicHashSet (intinitialcapacity) {Map=NewHashmap<>(initialcapacity); }  /*** Constructs a top capacity and load factor of the HashSet, using LINKEDHASHMAP implementation, this method is not external, but applied to linkedhashset.     * The parameter dummy no practical meaning, just a sign, please ignore. */HashSet (intInitialcapacity,floatLoadfactor,Booleandummy) {Map=NewLinkedhashmap<>(initialcapacity, loadfactor); }    /*** Return iterator, using HashMap's Keyset method to return, which also verifies that the value of HashSet is actually stored on the HashMap key*/     PublicIterator<e>iterator () {returnMap.keyset (). iterator (); }    /*** Size is also through the HashMap size method*/     Public intsize () {returnmap.size (); }   /*** Judging whether it is empty, but also by HashMap the IsEmpty method to judge*/     Public BooleanIsEmpty () {returnMap.isempty (); }    /*** If HashSet contains an element, returns true * More specifically, returns True if and only if HashSet satisfies the Objects.equals method; * Objects is a new class for JDK1.7 to refine obj ECT related methods, such as equals to avoid null pointer anomalies, are all static method; * Similarly, the bottom layer is achieved by HashMap ContainsKey;*/     Public Booleancontains (Object o) {returnMap.containskey (o); }    /*** If the hashset does not specify an element, the specified element is added. * More specifically, the element that is not satisfied with the Objects.equals method is added. Returns False if it is already there;*/     Public BooleanAdd (e e) {returnMap.put (e, PRESENT) = =NULL; }     /*** If there is a specified element in the HashSet, delete it.     More specifically, there are elements that satisfy the Objects.equals method. * Returns True if HashSet contains the element. Or, returns True if this set is changed because of a call*/     Public BooleanRemove (Object o) {returnMap.Remove (o) = =PRESENT; }    /*** Call HashMap's Clear method to clear*/     Public voidClear () {map.clear (); }  /*** Shallow copy operation, call HashMap's Clone method to implement*/@SuppressWarnings ("Unchecked")     PublicObject Clone () {Try{HashSet<E> Newset = (hashset<e>)Super. Clone (); Newset.map= (Hashmap<e, object>) Map.clone (); returnNewset; } Catch(clonenotsupportedexception e) {Throw NewInternalerror (e); }    }    /*** Serialization of private write methods, HashSet total capacity, load factor, actual capacity, elements written to the output stream ObjectOutputStream, JVM serialization by reflection call*/    Private voidWriteObject (java.io.ObjectOutputStream s)throwsjava.io.IOException {//Write out any hidden serialization magicS.defaultwriteobject (); //Write out HASHMAP capacity and load factorS.writeint (Map.capacity ());        S.writefloat (Map.loadfactor ()); //Write out SizeS.writeint (Map.size ()); //Write elements in the proper order.         for(e e:map.keyset ()) S.writeobject (e); }    /*** Deserialize the private Read method, will hashset total capacity, load factor, actual capacity, elements through the ObjectInputStream stream sequentially read, similarly, the JVM reflection call;*/    Private voidReadObject (java.io.ObjectInputStream s)throwsjava.io.IOException, ClassNotFoundException {//Read in any hidden serialization magicS.defaultreadobject (); //Read capacity and verify non-negative.        intCapacity =S.readint (); if(Capacity < 0) {            Throw NewInvalidobjectexception ("Illegal capacity:" +capacity); }        //Read load factor and verify positive and non NaN.        floatLoadfactor =s.readfloat (); if(loadfactor <= 0 | |Float.isnan (Loadfactor)) {            Throw NewInvalidobjectexception ("Illegal load factor:" +loadfactor); }        //Read size and verify non-negative.        intSize =S.readint (); if(Size < 0) {            Throw NewInvalidobjectexception ("Illegal size:" +size); }        //Set The capacity according to the size and load factor ensuring that//The HASHMAP is at least 25% full but clamping to maximum capacity.Capacity = (int) math.min (Size * math.min (1/loadfactor, 4.0f), hashmap.maximum_capacity); //Create backing HashMapMap = (((hashset<?>) This)instanceofLinkedhashset?NewLinkedhashmap<>(capacity, loadfactor):NewHashmap<>(capacity, loadfactor)); //Read in all elements in the proper order.         for(inti=0; i<size; i++) {@SuppressWarnings ("Unchecked") e e=(E) s.readobject ();        Map.put (E, PRESENT); }    }   /*** JDK1.8 New method, returns an iterator, but the iterator is not the original one-way access, but belongs to a segmented iterator, that is, the element can be accessed through multi-threaded * parallel;*/     PublicSpliterator<e>Spliterator () {return Newhashmap.keyspliterator<> (map, 0,-1, 0, 0); }}

HashSet Precautions:

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.

The source code is based on JDK9.

Java-hashset Source

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.