After we have learned HashMap, it is very easy to look at HashSet. Because HashSet is implemented based on HashMap.
Open the source code of HashSet, you can see that a HashMap is maintained
1. Member variables
// The element used to store HashSet private transient HashMap<E , Object> map ; // This Object is used to fill the value of HashMap . private static final Object PRESENT = new Object() ;
Second, the construction method
public HashSet() { map = new HashMap<>(); }
As you can see, the default construction is to instantiate the HashMap of member variables.
3. Methods
public int size() { return map.size(); }
size is the size of HashMap.
public boolean contains(Object o) { return map.containsKey(o); }
Because HashSet only uses the keys of HashMap, use the containsKey method of HashMap
public boolean add(E e) { return map.put(e, PRESENT)==null; }
When adding, just add the element to be added and the Object object that just filled the Value to the HashMap
public boolean remove(Object o) { return map.remove(o)==PRESENT; }Remove remove method using HashMap
Is not it simple. As long as you know that HashSet maintains a HashMap, then the operation of HashSet is the operation of the key of HashMap that you are familiar with.