Source code analysis of HashSet in Java Collection Series
1. Introduction to HashSet is a typical implementation of the Set interface. It stores the elements in the Set according to the Hash algorithm and has good access and search performance. It has the following features: it is not guaranteed that the set's iterative sequence HashSet is not synchronized. If multiple threads access a HashSet at the same time, the code must be used to ensure that the element value of the synchronization set can be null. When an element is saved to the HashSet set, the HashSet calls the hashCode () of the object () method to obtain the hashCode value of the object, and then determine the storage location of the object in the HashSet according to the value. In a Hash set, two equal elements cannot be stored at the same time. The criterion for determining that two elements are equal is that two objects are compared using the equals method and the HashCode method return values of the two objects are equal. The following example illustrates the above features:
Public class Person {String name; int age; public Person (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} // if the Object name and name are the same, true public boolean equals (Object obj) {if (obj = null) return false; if (this. name. equals (Person) obj ). name) & this. age = (Person) obj ). age) return true; else return false ;}}
Add two Person object instances with the same name and age to the HashSet:
public class HashSetDemo{ public static void main(String[] args) { HashSet<Person> hs = new HashSet<>(); Person p1=new Person("xujian", 23); Person p2=new Person("xujian", 23); hs.add(p1); hs.add(p2); for(Person p:hs) { System.out.println(p.name+"---"+p.age); } }}
It can be seen that two Person objects with the same name and age are stored in HashSet. Next, we will rewrite the hashCode method of the Person class so that it returns the same HashCode.
Public class Person {String name; int age; public Person (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public int hashCode () {// return 1 ;} // if the Object name and name are the same, true public boolean equals (Object obj) {if (obj = null) return false; if (this. name. equals (Person) obj ). name) & this. age = (Person) obj ). age) return true; else return false ;}}
If you add an element to a HashSet again, you will find that only one HashSet is saved. In a HashSet, each slot that can store elements is usually called a "Bucket". If multiple elements have the same hashCode, but the equals method returns false, you need to store multiple elements in a bucket. Back to Top 2. HashSet source code analysis 1. The underlying architecture of the constructor HashSet is actually implemented by HashMap. The four constructors correspond to the corresponding HashMap.
// Construct a new, empty HashSet. The default initial capacity of the underlying HashMap instance is 16, and the load factor is 0.75 public HashSet () {map = new HashMap <> () ;}// construct a new set public HashSet (collection <? Extends E> c) {map = new HashMap <> (Math. max (int) (c. size ()/. 75f) + 1, 16); addAll (c) ;}// construct a new empty set, its underlying HashMap instance has the specified initial capacity and the specified loading Factor public HashSet (int initialCapacity, float loadFactor) {map = new HashMap <> (initialCapacity, loadFactor );} // construct a new empty set. The underlying HashMap instance has the specified initial capacity and the default loading Factor 0.75 public HashSet (int initialCapacity) {map = new HashMap <> (initialCapacity );}
2. Common HashSet method boolean add (E e): If the set does not contain the specified element, add the specified public boolean add (E e) {// call the put Method of map, where the value is the static Object return map. put (e, PRESENT) = null;} void clear (): removes all public void clear () {map from this set. clear ();} Object clone (): returns a superficial copy of The HashSet instance.
Public Object clone () {try {// call the clone method HashSet of the parent class <E> newSet = (HashSet <E>) super. clone (); newSet. map = (HashMap <E, Object>) map. clone (); return newSet;} catch (CloneNotSupportedException e) {throw new InternalError (e );}}
Boolean contains (Object o): If this set contains the specified element, true public boolean contains (Object o) {return map is returned. containsKey (o);} boolean isEmpty (): If this set does not contain any elements, true public boolean isEmpty () {return map. isEmpty ();} Iterator <E> iterator (): returns the public Iterator <E> iterator () {return map that iterates on the elements in this set. keySet (). iterator ();} boolean remove (Object o): If the specified element exists in this set, remove the 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 ();} Back to Top 3. Sample Code of the HashSet Application
Public class HashSetDemo {public static void main (String [] args) {HashSet <String> hs1 = new HashSet <> (); // create a new HashSet System with a default size of 16 and a loading Factor of 0.75. out. println ("Call the add function"); hs1.add ("Hello"); hs1.add ("World"); hs1.add ("nihao "); hashSet <String> hs2 = new HashSet <> (hs1); // constructs a HashSet System that contains elements in hs1. out. println ("Call the remove function"); hs1.remove ("Hello"); for (String str: hs1) System. out. println (str); System. out. println ("Call clone function"); HashSet <String> hs3 = (HashSet <String>) hs2.clone (); for (String str: hs3) System. out. println (str); System. out. println ("using Iterator to traverse elements in HashSet"); 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 ());}}