First, source code analysis
Public classHashset<e>extendsAbstractset<e>ImplementsSet<e>, cloneable, java.io.serializable{Private transientHashmap<e,object>map; Private Static FinalObject PRESENT =NewObject (); //constructor function. New an empty HASHMAP (HashMap default initialization capacity is 16, and the default load factor is 0.75). PublicHashSet () {map=NewHashmap<>(); } //constructor function. New one HashMap and adds a collection to it. Customize the initialization capacity based on the size of the collection PublicHashSet (collection<?extendsE>c) {map=NewHashmap<> (Math.max (int) (C.size ()/.75f) + 1, 16)); AddAll (c); } //constructor function. New an empty HASHMAP, custom initialize capacity and load factor PublicHashSet (intInitialcapacity,floatloadfactor) {Map=NewHashmap<>(initialcapacity, loadfactor); } //constructor function. New an empty HASHMAP, custom initialization capacity PublicHashSet (intinitialcapacity) {Map=NewHashmap<>(initialcapacity); } //get an iterator, which is a collection of key values for a map PublicIterator<e>iterator () {returnMap.keyset (). iterator (); } //get the number of elements, that is, the number of HASHMAP elements Public intsize () {returnmap.size (); } //Determines whether the HashMap is empty or not. Public BooleanIsEmpty () {returnMap.isempty (); } //Determine If an element is included, that is, if there is no element in the HashMap key. Public Booleancontains (Object o) {returnMap.containskey (o); } //adds a single element. That is, add an element of key E to HashMap, and value is the PRESENT object//adding success returns True. Adding duplicate elements (return false) is not allowed. Public BooleanAdd (e e) {returnMap.put (e, PRESENT) = =NULL; } //Delete an element Public BooleanRemove (Object o) {//HashMap Deletes this element based on key, and if the deletion succeeds, it returns the element and must be PRESENT. returnMap.Remove (o) = =PRESENT; } //clears the collection, that is, the map clears the collection Public voidClear () {map.clear (); }}
Second, summary
1). HashSet is actually maintaining a HashMap. The HashSet element corresponds to the key in the HashMap, and the value of this HashMap all keys is PRESENT.
2). Since HashSet is a collection of all the keys of a HashMap, because key can be empty and cannot be duplicated, HashSet is also allowed to be empty and not allow repeating elements.
In this way, if you understand HashMap, HashSet will be very simple.
~~
Java Collection-HashSet