HashSet is implemented based on the implementation--hashmap of the hash table in the Java class Library, unlike HashMap, which holds a single element instead of a key-value pair.
In HashSet, use HashMap to store elements:
private transient hashmap<e,object> map;
As seen from this map type, it stores the hashset element as a HashMap key. Because the value position of the key-value pair is empty, a value is used to occupy the position of the value of the key-value pair:
Private static Final Object PRESENT = new Object ();
present is set to static so that it belongs to a class so that all HashSet instances use this object to save storage space.
Let's take a look at some of the operations in HashSet.
(1) Add an element to the HashSet
Public boolean Add (E e) { return Map.put (E, PRESENT) ==null; }
The put method of HashMap is already mentioned in the implementation--hashmap of the hash table in the Java class Library.
(2) Removing an element from the HashSet
public boolean remove (Object o) { return Map.Remove (o) ==present; }
The Remove method of HashMap is also mentioned in the implementation--hashmap of the hash table in the Java class Library .
(3) See if HashSet contains an element
Public Boolean contains (Object o) { return Map.containskey (o); }
The ContainsKey method of HashMap is also mentioned in the implementation--hashmap of the hash table in the Java class Library .
The implementation of hash table in Java class Library--hashset