Sketch
When writing the HashMap, I mentioned that the Set is implemented based on the Map. The HashSet is implemented based on the HashMap, and the data of the HashSet is saved as the Key value of the HashMap. Therefore, the elements in the HashSet are not repeatable, unordered, null elements are allowed, and the thread is not safe.
Source code analysis
HashSet field
//Implementation based on HashMap
private transient HashMap map;
//Virtual value
private static final Object PRESENT = new Object();
Construction method
/**
* Default no parameter construction, initializing an empty HashMap
*/
public HashSet() {
map = new HashMap<>();
}
/**
* Specify capacity construction
*/
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**
* Specify capacity and load factor
*/
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/**
* Specify the capacity and load factor to construct a new collection. Non public has access rights
* Only LinkedHashSet involves
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
/**
* Specify the collection collection construction
*/
public HashSet(Collection c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
From here, we can see that HashSet is based on the implementation of HashMap
add method
Use the put method of the HashMap to complete the add operation of the HashSet. Because the key of the HashMap cannot be repeated, the elements in the HashSet will not be repeated. The source code is as follows
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
remove method
Call the remove method of HashMap
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
contains method
Because the elements of the HashSet are saved as the key value of the HashMap, query whether to include this key
public boolean contains(Object o) {
return map.containsKey(o);
}
iteration
Get iterator of KeySet of HashMap
public Iterator iterator() {
return map.keySet().iterator();
}
clone method
Belongs to shallow clone
public Object clone() {
try {
HashSet newSet = (HashSet) super.clone();
newSet.map = (HashMap) map.clone();
return newSet;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
summary
HashSet is implemented based on HashMap, which is as unordered as HashMap and unsafe for threads. The key of HashMap is not repeatable to realize that HashSet does not contain duplicate elements
Write at the end: welcome to leave a message to discuss, click "pay attention", don't get lost, add attention, keep updating!