public V put(K key, V value) {
//如果 HashMapEntry 数组为空 进行初始化操作
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//如果key==null 执行nullkey 操作
if (key == null)
return putForNullKey(value);
//通过key 计算 hash值
int hash = sun.misc.Hashing.singleWordWangJenkinsHash(key);
//通过计算出来的hash值 和 HashMapEntry 数组的长度
// 计算出 这个key对象在HashMapEntry 数组的 索引值 index
int i = indexFor(hash, table.length);
//table[i] 不为null 依据链表的数据结构 通过next 进行遍历
for (HashMapEntry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//如果当前节点key 的hash 和 传递进来的这个key的hash 相等
// 并且 当前节点key 和 传递进来的这个key 相等
// (分为基础数据类型 和 引用数据类型)
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
//用新的 value值 替换 当前节点的 value值
e.value = value;
e.recordAccess(this);
//并且返回老的value值
return oldValue;
}
}
//数组的第i个对象 table[i] 如果为null
// 直接新建一个HashMapEntry对象
modCount++;
addEntry(hash, key, value, i);
return null;
}
//nullkey put 操作
private V putForNullKey(V value) {
//table[0] 有HashMapEntry
// 将value赋值给这个元素的value 并且返回旧的value
for (HashMapEntry<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;
}
}
//table[0] 没有HashMapEntry 将这个元素添加到talbe[0]位置
modCount++;
addEntry(0, null, value, 0);
return null;
}
//增加一个HashMapEntry对象
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ?
sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
//创建 HashMapEntry
void createEntry(int hash, K key, V value, int bucketIndex) {
//把当前index 的那个 HashMapEntry 记录下来
HashMapEntry<K,V> e = table[bucketIndex];
//根据 key value 新建一个HashMapEntry
// 并把这个新建的 HashMapEntry设置为当前index对应的HashMapEntry
// 同时把这个新建的HashMapEntry的next节点
// 设置为e (原来的那个HashMapEntry)
table[bucketIndex] = new HashMapEntry<>(hash, key, value, e);
size++;
}
// hashmap 是 数组+ 链表结构
static class HashMapEntry<K,V> implements Map.Entry<K,V> {
final K key; //key
V value; //value
HashMapEntry<K,V> next; //链表结构的next 指针
int hash; //key 的hash
/**
* Creates new entry.
*/
HashMapEntry(int h, K k, V v, HashMapEntry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}