1.HashMap的基礎結構
在1.7中,HashMap 底層是基於 數組 + 鏈表的結構組成。在1.8中,如果鏈表的長度大於一定的值,鏈表會轉成紅黑樹。
2.HashMap的參數(1.8)
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
...
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
...
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
DEFAULT_INITIAL_CAPACITY:16,數組的初始值,沒太多好解釋的。
MAXIMUM_CAPACITY:最大值,基本上不會達到這個值。
DEFAULT_LOAD_FACTOR:size / capacity(DEFAULT_INITIAL_CAPACITY)
threshold: capacity * load factor,超過這個閾值會rehash。
//一個桶的樹化閾值
//當桶中元素個數超過這個值時,需要使用紅黑樹節點替換鏈表節點
//這個值必須爲 8,要不然頻繁轉換效率也不高
static final int TREEIFY_THRESHOLD = 8;
//一個樹的鏈表還原閾值
//當擴容時,桶中元素個數小於這個值,就會把樹形的桶元素 還原(切分)爲鏈表結構
//這個值應該比上面那個小,至少爲 6,避免頻繁轉換
static final int UNTREEIFY_THRESHOLD = 6;
//哈希表的最小樹形化容量
//當哈希表中的容量大於這個值時,表中的桶才能進行樹形化
//否則桶內元素太多時會擴容,而不是樹形化
//爲了避免進行擴容、樹形化選擇的衝突,這個值不能小於 4 * TREEIFY_THRESHOLD
static final int MIN_TREEIFY_CAPACITY = 64;
3.HashMap中DEFAULT_LOAD_FACTOR爲什麼是0.75
如果該值設爲0.5,會在hashmap容量達到一半時候就擴容。比如從16擴大32,從32到64,64到128,浪費的空間會越來越大。
而如果該值設置爲1,則每次空間使用完畢纔會擴容,put時候操作耗時會增加。
所以0.75是時間與空間的一個平衡。
4.put時候操作
1.7插入元素到單鏈表中採用頭插入法,1.8採用的是尾插入法
5.HashMap死循環
HashMap在併發執行put操作時會引起死循環,是因爲多線程會導致HashMap的Entry鏈表形成環形數據結構。