HashSet浅析 - 969251639/study GitHub Wiki
HashSet内部用一个HashMap的key来存储,如果懂HashMap则HashSet可以分分钟看懂
private transient HashMap<E,Object> map;
构造时初始化map
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
因为HashSet只用到了HashMap的key做为存储,那么HashMap的value对于HashSet来说是一个定值就可以了,所有的key存储的value都是一样
private static final Object PRESENT = new Object();
add方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
add方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
remove方法
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
循环遍历
public Iterator<E> iterator() {
return map.keySet().iterator();
}
所以,HashSet的所有操作都是对内部的map进行操作