一:hashmap的13 个成员变量
- static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
-> 数组默认初始容量:16
- static final int MAXIMUM_CAPACITY = 1 << 30;
-> 数组最大容量2 ^ 30 次方
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
-> 默认负载因子的大小:0.75
- static final int MIN_TREEIFY_CAPACITY = 64;
-> 树形最小容量:哈希表的最小树形化容量,超过此值允许表中桶转化成红黑树
- static final int TREEIFY_THRESHOLD = 8;
-> 树形阈值:当链表长度达到8时,将链表转化为红黑树
- static final int UNTREEIFY_THRESHOLD = 6;
-> 树形阈值:当链表长度小于6时,将红黑树转化为链表
- transient int modCount; -> hashmap修改次数
- int threshold; -> 可存储key-value 键值对的临界值 需要扩充时;值 = 容量 * 加载因子
- transient int size; 已存储key-value 键值对数量
- final float loadFactor; -> 负载因子
- transient Set< Map.Entry< K,V >> entrySet; -> 缓存的键值对集合
- transient Node< K,V>[] table; -> 链表数组(用于存储hashmap的数据)
二:构造方法
/**
* 默认无参构造方法:
* 初始容量16
* 负载因子0.75
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
/**
* 参数为初始容量
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 参数为初始容量 和 负载因子
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 设置可存储的 key-value 键值对最大值
* 返回值为传入参数最接近的且大于等于的2的n次方
* 传入参数 3 -> 4
* 传入参数 5 -> 8
* 传入参数 32 -> 32
* 传入参数 33 -> 64
*/
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 >= 1 << 30) ? 1 << 30 : n + 1;
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) {
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false,evict);
}
}
}
三:Node< K,V > 存储结构