你應該瞭解:
0、HashSet本質還是hashmap,只不過把hashmap的value統一設置爲PRESENT
1、源碼閱讀順序(建議):hashtable→hashmap→hashset
2、new HashMap<>(Math.max((int) (c.size() / .75f) + 1, 16));每一個參數的含義
3、如何插入和刪除一個元素
4、線程不安全
繼承
- HashSet繼承AbstractSet抽象類和實現Set、Cloneable、Serializable接口。
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
protected AbstractSet() {
}
public boolean equals(Object o) {
***
}
public int hashCode() {
***
}
public boolean removeAll(Collection<?> c) {
***
}
}
內置元素
- 底層以HashMap來實現,set就是map的key,然後將map的value統一格式化爲PRESENT。
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size() / .75f) + 1, 16));
addAll(c);
}
如何添加一個元素
- hashset將map的
value
設置爲PRESENT
然後調用hashmap來創建。
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
如何刪除一個元素
- object o就是map裏面的key,將他傳到hashmap去刪除就可以,無需理會value,只有返回時以value來判斷是否刪除成功。
public boolean remove(Object o) {
return map.remove(o) == PRESENT;
}
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}