以add()方法爲例,查看hashSet的底層源碼實現,後面的源碼啃不動了。。。。就我理解是數組+鏈表;當鏈表結構達到8個時候,會將前面的8個鏈表轉換成二叉樹結構,而不是以第8個鏈表爲根節點,往後依次形成二叉樹,即將數組+鏈表變成了數組+二叉樹,所以最終的結構可能是:數組+鏈表+二叉樹,其中二叉樹以數組爲基礎,而不是以鏈表爲基礎,即不會在鏈表後面形成二叉樹,而是將鏈表(達到8個結點)轉換成二叉樹。
public boolean add(E e) {
//第一次返回null,即第一次添加成功
return map.put(e, PRESENT)==null;
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
hash(key)方法:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
hashCode()方法:
//調用非java接口
//此處調用的object的原生hashCode()方法
public native int hashCode();
transient Node<K,V>[] table;
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//初始化table爲null
if ((tab = table) == null || (n = tab.length) == 0)
//resize()方法擴容,返回Node[],數組大小是16
n = (tab = resize()).length;
//以下判斷簡寫成15&hash,進一步寫成:15 & ((hx = ((Object)obj).hashCode()) ^ (hx >>> 16))
//hx是一個int類型的臨時變量,obj是任意類型,基本或引用數據類型
//15 & ((hx = ((Object)obj).hashCode()) ^ (hx >>> 16))
//等價於
//((Object)obj).hashCode() % 16;即tab[]數組索引在0~15之間
//用Object強轉是因爲其調用的是Object原生的hashCode()方法,而非其他重寫的hashCode()方法
//此處if判斷,正是避免重複元素的關鍵,相同元素不會進行newNode
if ((p = tab[i = (n - 1) & hash]) == null)
//返回一個Node對象,其值是傳入的key,Node對象作爲Node<K,V>[]中的第i個元素
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//對於Set集合來說,判斷是否是同一個元素
//對於Map集合來說,判斷key是否相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//此處的p既是Node<K,V>[]中已存在的node對象
e = p;
//對於Set而言,判斷元素是否是二叉樹
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//對於Set集合而言,創建鏈表結構
for (int binCount = 0; ; ++binCount) {
//p是數組中存儲的Node元素,同時也是鏈表中的結點元素
if ((e = p.next) == null) {
//新創建一個Node對象,並且作爲上一個Node對象的下一個元素,即鏈表結構
p.next = newNode(hash, key, value, null);
//最大值是8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//判斷鏈表中的元素是否是同一個元素
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//對於Set集合而言,同一個元素,返回一個Object地址
//對於Map而言,判斷Map中key是否存在,新值覆蓋舊值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
//新值覆蓋原來的值
e.value = value;
afterNodeAccess(e);
//返回舊值
return oldValue;
}
}
++modCount;
//threshold閾值,剛開始是16*0.75=12
if (++size > threshold)
//當添加完第12個元素後進行擴容,同時將原來的Node<K,V>[]數組中的元素全部添加到新的數組中(32)
resize();
afterNodeInsertion(evict);
//每次添加新元素都返回Null
return null;
}
final Node<K,V>[] resize() {
//開始初始化爲null
//在添加一個元素後,table不爲null,大小是16
Node<K,V>[] oldTab = table;
//16
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//開始初始化爲0
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//newCap = 32,容量擴大一倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//閾值擴大一倍,24
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else {
//下面的英文解釋初始化爲0,使用默認值
// zero initial threshold signifies using defaults
//static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
newCap = DEFAULT_INITIAL_CAPACITY;//16
//static final float DEFAULT_LOAD_FACTOR = 0.75f;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//第一次添加元素時創建大小是16的Node數組
//擴容時創建大小是32的Node<K,V>[]數組
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//將新的Node<K,V>[]數組賦給成員變量table
table = newTab;
if (oldTab != null) {
//將原Node<K,V>[]數組中的元素全部放入新的newTab中
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//獲取原數組中的node對象賦給e
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//判斷是否是數組,e.next == null 代表數組
if (e.next == null)
//同上15&hash,等價於對32取模,結果是0~31,將e放入新的Node<K,V>[]數組中
newTab[e.hash & (newCap - 1)] = e;
//判斷是否是樹結構
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
//鏈表
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
//獲取鏈表中下一個元素
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
//返回新數組
return newTab;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
//擴容後大小是64
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
//將鏈表的元素轉換成樹結構
TreeNode<K,V> 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);
}
}
replacementTreeNode()方法:
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
treeify()方法:
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceInsertion(root, x);
break;
}
}
}
}
moveRootToFront(tab, root);
}