一、在jdk1.7中,HashMap存储空间模型是:数组加链表(元素是Entry(链表结构)的数组),数组用来存放key的hash值,链表用来存放键值对值,每一个数组元素对应一个链表,数组和链表的元素都是Entry对向。
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold); //默认是threshold=16
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
private void inflateTable(int toSize) {
int capacity = roundUpToPowerOf2(toSize);
// loadFactor 负载因子
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
private V putForNullKey(V value) {
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
// 满足条件时重新初始化table并且计算之前已经插入的元素的hash的值和链表中的位置
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
上述代码是jdk1.7中HashMap的put方法的源代码,可以看到当添加一个值时:
1、若table是空数组,初始化一个大小为16的数组;
2、若添加的键值对的key是null,则插入到数组第0个链表中,首先判断这个链表中是否已经存在一个key==null的键值对,若存在则替换旧的值并返回旧值;若不存在使用”头插法”将这个新Entry放到链表的头部,将其next 指向先前的Entry;
3、首先计算key的哈希值,hash值表示要将这个键值对插入到哪个链表中,然后判断这个链表中是否已经存在一个key的键值对,若存在则替换旧的值并返回旧值;若不存在使用”头插法”将这个新Entry放到链表的头部,将其next 指向先前的Entry;
二、在jdk1.8中,HashMap的put的源代码为:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node 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 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)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;
}
可以看到有这样一段代码: