For HashSet, it is implemented based on HashMap, and the underlying uses HashMap to preserve the elements. Today we will simply analyze the implementation of it.
Simple analysis of HashSet--the composition of member variables of HashSet
Public class extends Implements Set<e>, cloneable, java.io.Serializableprivatetransient hashmap<e,object> map; // Dummy value to associate with a Object in the backing Map Private Static Final New Object ();
HashSet is constructed by creating a hashmap.
Public HashSet () { new hashmap<>();}
Second, some operations of HashSet are based on the HashMap created above
PublicIterator<e>iterator () {returnMap.keyset (). iterator ();} Public intsize () {returnmap.size ();} Public BooleanIsEmpty () {returnmap.isempty ();} Public Booleancontains (Object o) {returnMap.containskey (o);} Public BooleanAdd (e e) {returnMap.put (e, PRESENT) = =NULL;//present is a member variable of HashSet} Public BooleanRemove (Object o) {returnMap.Remove (o) ==present;//present is a member variable of HashSet} Public voidClear () {map.clear ();}
Friendship Link
- The principle of HashMap:http://www.cnblogs.com/huhx/p/baseusejavahashmap1.html
Simple analysis of Java Foundation---->hashset (i)