hashmap採用數組和鏈表以及紅黑樹的基礎數據結構,數組的查找時間複雜度爲常數,鏈表爲o(n),而紅黑樹是一種平衡樹,穩定在log(n)。可以有很快的查找速度。
先來看看放入元素的過程:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
先會對key做一次hash:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
h的默認值爲0,將其不帶符號的右移16位,再與key的hashcode做異或運算,也就是每位保留了爲1的值,也就是key的hashcode,而它是32位的,也就是,如果整個內存當成一個數組,其關鍵字域和下標域,也就是has桶的個數是相同的。但這不太可能,初始化hashmap的時候,默認是16,所以很顯然,這個對key作hash的值仍然不能直接使用。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//TreeNode繼承自Node
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//初始化,或者擴容
n = (tab = resize()).length;
//注意這,n-1與一個數作與運算,其值肯定會小於等n-1
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;
}
以上邏輯爲,通過(n - 1) & hash找到tab的下標,如果tab[i]爲空,則直接封裝一個node插入,如果,不爲空,則判斷其hash值並且key是否相等,如果相等,則不作處理,返回的值爲p的value,
如果其中有一個不相同,則判斷其類型是否是TreeNode,如果是,則按照紅黑樹的插入方式,如果不是則按照鏈表的插入方式。
所以,當向hashmap插入相同的key時,會根據!onlyIfAbsent || oldValue == null來判斷,onlyIfAbsent 爲false,所以會更新value。