本文主要從HashSet的add方法開始,去了解HashSet存儲數據的過程以及它的一些數據結構。
直接開始吧
以下是HashSet的add方法源碼:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
map的定義是private transient HashMap<E,Object> map;
而PRESENT的定義是private static final Object PRESENT = new Object();由於是static修飾,類加載後PRESENT就是一個單例的Object對象。
可以看到HashSet存儲數據方法實際用到的是HashMap的put方法
接着走:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
這裏key就是我們要存的值了,value則是那個單例的Object對象。方法調用了HashMap的putVal方法,並對key做了hash(key)的處理,可以看看hash(key)方法的內部:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
key如果是空的話,方法返回0,如果不是空的話返回key的哈希值前十六位和後十六位的異或(這實際上是一種儘量避免哈希值相同而做的處理)
接着回來看putVal:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> 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<K,V> 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<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
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;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
可以拆分下來一點點看,
Node<K,V>[] tab; Node<K,V> p; int n, i;
tab是Node類的一個數組,p是Node的一個引用。n和i還沒發揮作用。
Node類是HashMap的一個內部類,代碼如下:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
可以看到Node實際存儲的是上面hash(key)方法返回的值,key,value,和一個Node的引用類型next,還有一些常見的方法,這裏不一一講解。
接着看putVal的下一行
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
第一行很明顯,把table賦值給tab並判斷tab這個數組是不是爲空,並把數組長度賦值給n。如果爲空的話,調用resize()方法,並將方法返回值賦給tab,再將tab的長度賦給n。關於table定義如下
transient Node<K,V>[] table;
如果是第一次進入該函數table的值還是空的,沒錯,他在resize()方法進行初始化,resize()方法發揮的作用就是初始化容器大小和擴容:
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
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"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
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;
}
感覺挺長,一點點看,變量賦值
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
將table賦值給了oldTab,然後判斷它是不是空的,如果是空的,那麼oldCap的值就是0,不是空的oldCap值就等於table的長度。把threshold賦值給oldThr,threshold實際上是一個閾值(int),它控制着容器存儲到什麼程度開始擴容,resize()的代碼會有體現到。將newCap和newThr初始化爲0。
接着一行行走:
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
這裏可以看到判斷了當前容器長度(table的長度)是否大於0,很明顯這段是擴容時候用到的代碼。判斷當前容器長度有沒有超過最大容器長度MAXIMUM_CAPACITY
static final int MAXIMUM_CAPACITY = 1 << 30;
挺大的,超過的話直接返回了oldTab,看來就是擴容不了。如果沒有超過MAXIMUM_CAPACITY,可以看到oldCap左移了以爲,實際上就是擴容了一倍。然後閾值也跟着擴大一倍。
接下來是
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
這和HashMap的構造函數有關,不在我們討論範圍內
接着
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
這個是oldCap小於等於零而且oldThr也不大於零的情況,說白了就是進入初始化的一段
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
這裏就可以看出來HashMap中Node<K,V>[]的一個默認長度是16
static final float DEFAULT_LOAD_FACTOR = 0.75f;
可以看出來初始的閾值是0.75乘以16就是12。
接着往下:
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
這裏也和HashMap的構造函數相關,不再討論
go on(繼續)
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
將新的閾值賦值給了threshold,利用新的容器大小new了新的Node數組,並將其賦值給table,實際上現在容器存儲的數據還沒有轉移到新的容器中 ,下面的代碼就是完成這部操作的。也許直接看它會很蒙B,所以我先解釋一下 HashMap的數據結構數組散列:
畫的好像不是很美觀。。。橫框代表了Node的數組,其實就是我們上面說的table,圓則是Node節點,Node中的屬性next指向下一個節點。好了,開始看數據轉移的代碼吧,有點長所以寫到註釋裏了
if (oldTab != null) {
//循環原來的容器
for (int j = 0; j < oldCap; ++j) {
//定義一個Node e
Node<K,V> e;
//將循環到的數據賦值給e並判斷是不是空,如果是空,++j,下一個層循環
if ((e = oldTab[j]) != null) {
//將原數據位置賦值爲null,釋放空間
oldTab[j] = null;
//判斷下一個節點是不是空,如果是空的話說明這個Node在數組中且沒有下一個節點
if (e.next == null)
//直接將這個節點放到新容器下標爲e的hash屬性(兩個e的hashCode異或)與上新長度-1,這麼做不僅
//給元素新的下標,還可以防止數組下標越界
newTab[e.hash & (newCap - 1)] = e;
//這個是節點如果是樹的情況,我們之後再討論這種情況
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//數組中節點的next屬性不爲空
else { // preserve order
/*根據情況分爲兩組指針,一組爲擴容後進行了
newTab[e.hash & (newCap - 1)] = e(給元素新的位置)操作後
元素仍爲原來下標的頭指針loHead和尾指針loTail,另一組爲更新
元素位置後是原下標+原數組長度的位置的頭指針hiHead和尾指針
hiTail*/
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
//下面我寫的文字可能不太明瞭,將會在代碼下作圖演示這個過程
do {
//將next指向e.next
next = e.next;
//判斷新的元素位置是原位置還是 原位置+原數組長度
//等於0是原位置,這個地方我下面會具體討論
if ((e.hash & oldCap) == 0) {
//第一次賦值,loHead和loTail都將指向e指向的區域
if (loTail == null)
loHead = e;
//由於下面的while將e指向了next指向的區域,所以
//loTail.next即上一輪的e指向了上一輪e.next
else
loTail.next = e;
//確定loTial尾指針的地位
loTail = e;
}
//和上面的過程一樣
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
//如果尾指針loTail不爲空,說明存在鏈表,將頭結點放在原下標位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//如果尾指針hiTail不爲空,說明存在鏈表,將頭結點放在原下標+原數組長度位置
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
好,這裏來作圖解釋爲什麼(e.hash & oldCap) == 0時,新的元素位置是原來元素所在的下標
我們上面說到過,數組長度是2的次冪,初始是16,就拿16舉例,原來元素的位置是e.hash&(數組長度-1)的到的,這是putVal中的代碼,我們還沒講到,將在下一篇中說到。加入數組長度是16,那麼元素位置就是e.hash&01111得到的,我們看作是1xxxx&01111或0xxxx&01111
上面第五位的作用可能並不明顯,可以看看擴容後新的位置的計算newTab[e.hash & (newCap - 1)] = e;新的newCap擴容了一倍,原來是16的話,現在就是32
可以因爲擴容,新的元素位置可能是0xxxx也可能是1xxxx,擴容前位置只和xxxx有關。例如原來位置在1下標,這是00001或者10001和01111 &運算的結果,當擴容到32時,00001和10001與011111進行&運算結果就可能是1或者17(就是原下標加原數組長度),那麼我們總結上面的情況,當下標沒變就是0xxxx和原數組長度16 &運算,即0xxxx&10000結果是0,所以就出現了代碼中的判斷(e.hash & oldCap) == 0我們就可以確定它是擴容數組後,下標仍然沒變得那個元素。
接下來是遍歷節點的圖解,這個兩種情況是一樣的。
初始情況:
next = e.next;
if (loTail == null)
loHead = e;
loTail = e;
(e = next) != null
第一次結束
第二次
next=e.next
進入else:
else
loTail.next = e;
//確定loTial尾指針的地位
loTail = e;
接下來就是重複的過程了。
源碼分析1先寫到這吧。