文章目录
一、底层数据结构
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
HashMap是基于数组+链表实现, 数组类型为Entry<K,V>.
二、常用方法思维导图
三、部分源代码
1. put
public V put(K key, V value) {
if (table == EMPTY_TABLE) {//表为空时初始化容量
inflateTable(threshold);
}
if (key == null) // key为null
return putForNullKey(value);
int hash = hash(key); // 计算key的hash值
int i = indexFor(hash, table.length); // 根据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); //添加元素至table
return null;
}
添加元素的大致思路:
1.计算元素在table中的索引index.
2.创建Entry对象
3.table[index] = Entry
这样就涉及到2个问题:
1.索引重复
2.数组扩容
索引重复
//举个栗子
Map<String, String> map = new HashMap<>()
map.put("yk", "1111"); //index=13
map.put("ah", "1111"); // index=13
当执行map.put("yk", "