hashmap采用数组和链表以及红黑树的基础数据结构,数组的查找时间复杂度为常数,链表为o(n),而红黑树是一种近似平衡树,稳定在log2(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。