Java Collection series of HashSet source code analysis

Source: Internet
Author: User

I. Introduction of HashSet

HashSet is a typical implementation of the set interface, which stores the elements in the collection according to the hash algorithm, and has good access and lookup performance. Mainly has the following characteristics:

    • The set iteration order is not guaranteed
    • HashSet is not synchronous, and if multiple threads are accessing a hashset at the same time, they are guaranteed to be synchronized by code
    • The collection element value can be null

When an element is deposited into the HashSet collection, HashSet calls the object's Hashcode () method to get the Hashcode value of the object, and then determines where the object is stored in hashset based on that value. In a hash set, it is not possible to store two equal elements at the same time, while the criterion for judging two elements is equal, and two objects are compared by the Equals method and the return value of the Hashcode method of two objects is equal.

The following examples illustrate the above features:

 Public classperson{String name; intAge ;  PublicPerson (String name,intAge ) {         This. name=name;  This. age=Age ; }         PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }    //returns True when the name of the object is the same as the name     Public Booleanequals (Object obj) {if(obj==NULL)            return false; if(( This. Name.equals ((person) obj). Name && This. age==(person) (obj).) return true; Else            return false; }    }

At this point, add two person object instances of the same name and age to HashSet:

 Public class hashsetdemo{    publicstaticvoid  main (string[] args)    {        HashSet  New hashset<>();                person P1=new person ("Xujian", +);        person P2=new person ("Xujian", +);        Hs.add (p1);        Hs.add (p2);          for (person P:hs)        {            System.out.println (p.name+ "---" +p.age);     }}}

  

As can be seen, the hashset contains two person objects with the same name and age.

Next we rewrite the Hashcode method of the person class so that it returns the same hashcode.

 Public classperson{String name; intAge ;  PublicPerson (String name,intAge ) {         This. name=name;  This. age=Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public inthashcode () {//TODO Auto-generated method stubs        return1; }    //returns True when the name of the object is the same as the name     Public Booleanequals (Object obj) {if(obj==NULL)            return false; if(( This. Name.equals ((person) obj). Name && This. age==(person) (obj).) return true; Else            return false; }    }

Once again, adding an element to the hashset operation, you will find that HashSet only saved one at this time.

  

The slots for each of the hashset elements are often referred to as "buckets", and if multiple elements are hashcode the same, but returning false by the Equals method, you need to store multiple elements on a bucket.

Ii. hashset Source Code Analysis 1, the structure function

The bottom of the hashset is actually implemented by HashMap. Its four constructors correspond to corresponding HashMap respectively.

  //constructs a new, empty hashset, the default initial capacity of its underlying HashMap instance is 16, and the load factor is 0.75     PublicHashSet () {map=NewHashmap<>(); }    //constructs a new set that contains the elements in the specified collection     PublicHashSet (collection<?extendsE>c) {map=NewHashmap<> (Math.max (int) (C.size ()/.75f) + 1, 16));    AddAll (c); }   //constructs a new empty set whose underlying HASHMAP instance has the specified initial capacity and the specified load factor     PublicHashSet (intInitialcapacity,floatloadfactor) {Map=NewHashmap<>(initialcapacity, loadfactor); }    //constructs a new empty set whose underlying HASHMAP instance has the specified initial capacity and the default load factor 0.75     PublicHashSet (intinitialcapacity) {Map=NewHashmap<>(initialcapacity); }
2, HashSet common methods

  boolean Add (E): If the specified element is not already contained in this set, the specified element is added

 Public Boolean Add (e E)     {        // Call Map's Put method, where value is a static        object return map.put (e, PRESENT) = =null;    }

  void Clear (): Removes all elements from this set

 Public void Clear ()     {        map.clear ();    }

  Object Clone (): Returns a shallow copy of this HashSet instance

 public   Object Clone () { try   { //  hashset<e> newset = (hashset<e>) super  
    
     .clone ();            Newset.map 
     = (hashmap<e, Object> return   Newset;         catch   (Clonenotsupportedexception e) { throw  new   Internalerror (e); }    }

  Boolean contains (Object o): Returns true if this set contains the specified element

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

  boolean isEmpty (): Returns true if this set contains no elements

 Public Boolean IsEmpty ()     {        return  map.isempty ();    }

  iterator<e> Iterator (): Returns an iterator that iterates over the elements in this set

 Public Iterator<e> Iterator ()    {        return  map.keyset (). Iterator ();    

  boolean remove (Object o): If the specified element is present in this set, remove it

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

  int size (): Returns the number of elements in this set

     Public int size ()     {        return  map.size ();    }
Third, HashSet application example code
 Public classhashsetdemo{ Public Static voidMain (string[] args) {HashSet<String> HS1 =NewHashset<> ();//parameterless constructor creates a new hashset with a default size of 16 and a load factor of 0.75SYSTEM.OUT.PRINTLN ("Call the Add function"); Hs1.add ("Hello"); Hs1.add ("World"); Hs1.add ("Nihao"); HashSet<String> HS2 =NewHashset<> (HS1);//constructs a hashset that contains elements from the HS1System.out.println ("Call the Remove function"); Hs1.remove ("Hello");  for(String str:hs1) System.out.println (str); System.out.println ("Call the Clone function"); HashSet<String> hs3= (hashset<string>) Hs2.clone ();  for(String STR:HS3) System.out.println (str); System.out.println ("Traversing elements in HashSet using iterators"); Iterator<String> it=Hs2.iterator ();  while(It.hasnext ()) {System.out.println (It.next ()); } System.out.println ("Call the Size function");    System.out.print (Hs2.size ()); }}

Execution results

Java Collection series of HashSet source code analysis

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.