1. HashMap 关键名词: 16和0.75 是设计者结合空间和时间考虑的;
1. capacity : 当前数组容量,始终保持 2^n,可以扩容,扩容后数组大小为当前的 2 倍;
2. loadFactor :负载因子,默认为 0.75;
3. threshold :扩容的阈值,或者叫扩容临界值,等于 capacity * loadFactor;
4. 一个数组,数组中每个元素组成一个单向链表。;
单向链表关键名词:
Entry 类,包含四个属性:key, value, hash 值, next指向单向链表的下一个节点。
1.1 Entry 类:
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
2. put()方法简单介绍:当在链表中已经存在相同的hash和key时,覆盖原值,并将原值返回;
public V put(K key, V value) {
// 当插入第一个元素的时候,需要先初始化数组大小,即hashmap的大小;
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
// 如果 key 为 null,会将 entry 放到 table[0] 的位置
if (key == null)
return putForNullKey(value);
// 1. 对 key 求 hash 值
int hash = hash(key);
// 2. 找到hash值对应的数组下标
int i = indexFor(hash, table.length);
// 3. 遍历 数组中对应下标处的链表,比较 key 如果有重复,直接覆盖,put 方法返回旧值
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;
}
}
//hashmap在