JDK 1.6
public V put(K key, V value) {
// 当前key为null的时候会调用putForNullKey()方法来保存值
if (key == null)
return putForNullKey(value);
// 根据key的hashCode()的方法计算出hash值(如果key对象的类没有重写hashCode()方法,会调用Object的hashCode()方法)
// 然后利用HashMap的方法再次计算出hash值
int hash = hash(key.hashCode());
// 利用indexFor()方法计算出当前hash值应该放在table中的索引
int i = indexFor(hash, table.length);
// 根据索引遍历table里的链表,然后放入值
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// 当前key在链表中已经存在时,会覆盖该值,并将该值返回
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
// 新添加一条映射,将计数modCount+1
modCount++;
// 在table[i]处链表顶部添加一个Entry
addEntry(hash, key, value, i);
return null;
}
private V putForNullKey(V value) {
// 循环桶的0索引位置,一直到最后,如果找到key为null,就将值覆盖,并返回旧值
for (Entry<K,V> 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+1
modCount++;
addEntry(0, null, value, 0);
return null;
}
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
static int indexFor(int h, int length) {
// 利用位运算来达到求余的效果
return h & (length-1);
}
JDK 1.7
public V put(K key, V value) {
// 防止table没被初始化(其实在构造函数中就已经初始化了table)
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> 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;
}
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}