特點:
(1)HashMap是基於Hash表的
(2)HashMap的鍵和值都允許爲null
(3)HashMap不是線程安全的
HashMap執行過程(以默認構造函數爲例):
(1)定義HashMap。可以看到,執行沒有參數的構造方法之後,只將加載因子設爲默認加載因子爲0.75.
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
(2)調用put方法向HashMap中插入值
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
可以看到,put方法的作用是在map中將Key和Value關聯在一起。如果Map中已經包含這個Key所對應的映射,則將值進行替換。調用put方法後,會返回與該Key綁定的上一個Value值。若以往Map中不存在該Key對應的映射,則返回Null。可以看到,put(K key,V value)方法實際上調用的是putVal(hash(key),key,value,false,true)方法,接下來進入該方法。
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;//執行1
if ((p = tab[i = (n - 1) & hash]) == null)//判斷該key所對應的索引位置是否爲null
tab[i] = newNode(hash, key, value, null);//若爲空則直接插入數組中
else {//若不爲null,則插入鏈表或紅黑樹中
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//如果key重複,則進行替換
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);//當元素個數大於8時,將鏈表轉爲紅黑樹
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;
}
可以看到,在初始情況下,由於table==null,會調用resize()方法,也就是代碼執行1處。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;
}
可以看到,該方法的作用是擴充HashMap的大小。當舊容量爲0的時候,會將默認初始容量16作爲新容量。否則,新容量就變爲原容量的2倍,然後將oldTab中的數據一一插入到newTab中。然後繼續看putVal方法(待續)。
(3)調用get方法獲取key所對應的值
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
可以看到調用get方法後,就會執行getNode(hash(key),key)方法獲取該key所對應的node節點,獲取到結點後,就會調用value方法獲取對應值。getNode(hash,key)代碼如下:
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {//獲取數組中在該索引位置的元素
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;//若剛好是數組中的元素,則返回該元素
if ((e = first.next) != null) {
if (first instanceof TreeNode)//如果是紅黑樹
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);//如果不是紅黑樹,逐個遍歷鏈表找出對應元素並返回
}
}
return null;
}
(4)總結
在調用put方法向HashMap中添加元素的時候,若初始容量爲0,會先將容量擴容爲默認初始容量爲16,然後當需要的容量查過舊容量*加載因子的時候,會將容量擴大爲之前容量的2倍,然後將之前的元素逐個插入到新數組及數組對應的鏈表或紅黑樹中。在插入的時候,首先根據key值計算Hash,然後計算出該元素在數組中的索引位置,再判斷該位置處是否爲Null,若爲空,則直接插入,若不爲空,則判斷是否爲紅黑樹節點,若是,則插入紅黑樹中,否則插入到鏈表中,在插入之後,再判斷鏈表長度是否大於8,若大於8,則將鏈表轉爲紅黑樹。
在調用get方法獲取對應值的時候,首先獲取key對應的hash,然後計算出該hash在數組中的索引位置,獲取該位置元素。然後再比較元素的key是否真的相同,若相同則返回該元素。然後逐個對比鏈表或紅黑樹中的元素,直到找到對應元素。
歡迎指正!