流程图:
hash冲突:是指通过hash运算后映射到数组的位置,此时这个位置已被其他元素所占用。
fail-fast:防止在迭代器Iterator 中 HashMap的元素被修改。
阅读源码的时候应该关注HashMap的几个特征:
- 一些重要的静态成员变量
// HashMap的最大容量:2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
// HashMap的最小容量:16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 默认的负载因子,主要用于计算HashMap的threhold
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 当节点中至少有八个元素时,节点从链表转化为红黑树的阀值
static final int TREEIFY_THRESHOLD = 8;
// 当节点中数量为六时,红黑树蜕化为链表的阀值
static final int UNTREEIFY_THRESHOLD = 6;
// 红黑树的最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
- HashMap中的一些静态方法
// 将Hash码的高位向右移与低位做异或,这样做的目的是为了保留高位特征,降低hash冲突
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 返回大于cap的最小二次方
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
- 初始化HashMap的过程
// 手动指定HashMap的容量和负载因子
public HashMap(int initialCapacity, float loadFactor)
// 手动指定HashMap的容量,使用默认负载因子
public HashMap(int initialCapacity)
// 容量和负载因子使用默认大小
public HashMap()
- 添加元素的过程
/**
* Implements Map.put and related methods.
*
* @param hash key的hash码
* @param key 添加元素的key
* @param value 添加元素的value
* @param onlyIfAbsent 如果为true,不改变已存在的valye
* @param evict 如果为false,说明是刚创建向hashMap中添加元素
* @return previous value, or null if none
*/
final V putVal(int</