Java source Reading HashSet

Source: Internet
Author: User

1 Types of signatures and annotations

 Public class Hashset<e>    extends abstractset<e>    implements Set<e>, cloneable,

This class implements the Set interface, which is supported by a hash table (actually a HashMap instance). There is no guarantee for the iteration order of the collection. In particular, it does not guarantee that the order will remain constant for a period of time (HashMap 's capacity to re-hash). This class allows null elements.

Note that this implementation is out of sync. If multiple threads access the hash set concurrently, and at least one thread modifies the collection, it must be synchronized externally. This is usually done by synchronizing on some objects that naturally encapsulate the collection. If no such object exists, then the collection should use the Collections.synchronizedSet method "wrapper". This is best done at creation time to prevent accidental non-synchronous access to the collection:

Set s = collections.synchronizedset (new

The iterator returned by the class iterator method is quick to fail. This mechanism is described in detail in the HashMap section.

2 Properties

Static Final long serialversionuid = -5024744406713321676l; Private transient hashmap<e,object> map; // a virtual value in map Private Static Final New Object ();

HashSet is implemented through HASHMAP, so the internal map reference, set value corresponds to the key in the map, but each time the map insertion needs to be <key,value> key value pairs, so there is a virtual value object, is present.

3 Construction methods

//1 Default PublicHashSet () {map=NewHashmap<>(); }//2 construct by collection PublicHashSet (collection<?extendsE>c) {map=NewHashmap<> (Math.max (int) (C.size ()/.75f) + 1, 16));    AddAll (c); }//3 specifying the initialization capacity and load factor for the HashMap PublicHashSet (intInitialcapacity,floatloadfactor) {Map=NewHashmap<>(initialcapacity, loadfactor); }//4 Specifying the initialization capacity of the HashMap PublicHashSet (intinitialcapacity) {Map=NewHashmap<>(initialcapacity); }//5 Specify initialization capacity and load factor, internally via LinkedhashmapHashSet (intInitialcapacity,floatLoadfactor,Booleandummy) {Map=NewLinkedhashmap<>(initialcapacity, loadfactor); }

Note: The dummy parameter of the constructor method 5 actually has no special meaning, the only function is to distinguish the constructor Method 3 (method overload) by one more parameter.

4 Common methods

(1) Add

 Public Boolean Add (e e) {        return map.put (e, PRESENT) = =null;    }

(2) Remove

 Public Boolean Remove (Object o) {        return map.remove (o) = =PRESENT;    }

(3) contains

 Public Boolean contains (Object o) {        return  map.containskey (o);    }

(4) Other common

 Public Iterator<e> Iterator () {        return  map.keyset (). Iterator ();      Public int size () {        return  map.size ();    }  Public Boolean IsEmpty () {        return  map.isempty ();    }

The common methods of HashSet are implemented by invoking the HashMap method.

5 Other

(1) Clone

 Public Object Clone () {        try  {            HashSetSuper. Clone ();             = (hashmap<e, object>) Map.clone ();             return Newset;         Catch (clonenotsupportedexception e) {            thrownew  internalerror (e);        }    } 

(2) serialization and deserialization

//Serialization ofPrivate voidWriteObject ( s) {//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); }//deserializationPrivate voidReadObject ( s), ClassNotFoundException {//Read in any hidden serialization magicS.defaultreadobject (); //Read capacity (check non-negative).        intCapacity =S.readint (); if(Capacity < 0) {            Throw NewInvalidobjectexception ("Illegal capacity:" +capacity); }        //read load factor (cannot be null).        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); }        //calculate the required capacityCapacity = (int) math.min (Size * math.min (1/loadfactor, 4.0f), hashmap.maximum_capacity); //constructing the backing map would lazily create an array when the first element is//added, so check it before construction. Call Hashmap.tablesizefor to compute the//actual allocation size. Check Map.entry[].class since it ' s the nearest public type to//What is actually created.sharedsecrets.getjavaoisaccess (). Checkarray (S, map.entry[].class, Hashmap.tablesizefor (capacity)); //Constructing HashMap ObjectsMap = (((hashset<?>) This)instanceofLinkedhashset?NewLinkedhashmap<e,object>(capacity, loadfactor):NewHashmap<e,object>(capacity, loadfactor)); //adding a key-value pair to the HashMap         for(inti=0; i<size; i++) {@SuppressWarnings ("Unchecked") e e=(E) s.readobject ();        Map.put (E, PRESENT); }    }

(3) equals

The Equls method is not implemented in the HashSet class, but is inherited from the parent class Abstractset. The Equls implementation in Abstractset is as follows:

 Public Booleanequals (Object o) {if(O = = This)            return true; if(! (OinstanceofSet)) return false; Collection<?> C = (collection<?>) O; if(C.size ()! =size ())return false; Try {            returnContainsall (c); } Catch(ClassCastException unused) {return false; } Catch(NullPointerException unused) {return false; }    } Public BooleanContainsall (collection<?>c) { for(Object e:c)if(!contains (e))return false; return true; } Public Booleancontains (Object o) {Iterator<E> it =iterator (); if(o==NULL) {             while(It.hasnext ())if( () = =NULL)                    return true; } Else {             while(It.hasnext ())if(O.equals ( ()))return true; }        return false; }

equals first determines whether the same 1 objects are referenced, and if so, returns True.

Otherwise, the judgment is set type, or False if not.

If it is, determine if there is an equal size, or false if not.

If yes, the call to Containsall contains all elements, or False if True is returned.

Java source Reading HashSet

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: 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.