要了解HashSet就需要了解下HashMap,为什么?因为它维护的是一个HashMap,从它的构造器我们就可以明白了
public HashSet() {
map = new HashMap<>();
}
先说结论: <1> HashSet 不添加重复元素, 可添加一个NULL
<2> HashMap 底层维护 table表(数组)+双向链表+红黑树
<3> HashMap 扩容机制:初始化为 16 加载因子 0.75 thresdhold size*0.75 当前size>size*0.75 table表 两倍 扩容
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
添加调用的是 HashMap put方法:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
计算 hashcode 但并不只是 .hashcode 还有>>>16
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
真正添加元素 调用方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
------------------------------
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
满足条件 链表 树化:链表长度>=8 && table.size>=64 也就是说链表长度超过八 但是表的长度依旧没到64 还是不能树化
依旧按照 二倍扩容机制扩容
final void treeifyBin(Node[] tab, int hash) { int n, index; Node e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode hd = null, tl = null; do { TreeNode p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); }
这里要注意的是 table.size 是否 包括链表的长度?? 包括!!!



