核心问题
- HashMap中的位运算,为什么采用位运算,为什么是2的n次幂?
- HashMap中的扩容
- HashMap中的主要成员变量
- get方法
- put方法
寻找索引
HashMap的结构
- 主体还是一个存放Node节点的数组
- 产生hash冲突之后,进行链化,在对应索引位置形成链表
寻找索引
/**
1.7
*/
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* 返回数组下标
*/
static int indexFor(int h, int length) {
return h & (length-1); //第三步 取模运算
}
/**
1.8
*/
static final int hash(Object key) {
int h;
// h = key.hashCode() 为第一步 取hashCode值
// h ^ (h >>> 16) 为第二步 高位参与运算
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 分为三步:首先取出key的值(hashCode),然后高位运算,最后取模运算
- 确定key值时,采用对象的hashCode取模hash数组长度,保证元素在表中的分布是均匀的,且不会出现key值超过数组范围的问题
- 优化:由于取模运算效率较低,采用位运算的方式,也就是如1.7中返回数组下标的方法。
为什么是 hash值 & 数组长度-1
这里采用了一个非常巧妙的方式,使得位运算的效果完全等同于取模运算。通过 h & (length-1) 获得保存位的索引, 而HashMap底层数组的长度总是2的n次方,当length总是2的n次方时,h& (length-1)运算等价于对length取模。
1.8の优化
1.8优化了高位运算算法, 通过hashCode()的高16位异或低16位实现。
构造方法及创建过程
成员变量介绍
/**
* 该表在首次使用时初始化,并根据需要调整大小。分配时,长度始终是2的幂。
*/
transient Node<K,V>[] table;
/**
* map中 key-value的个数
*/
transient int size;
/**
* 要调整大小的下一个大小值(容量*负载系数)。 也就是扩容阈值
*/
int threshold;
/**
* 负载因子,默认0.75
*/
final float loadFactor;
构造方法
//无参构造
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//设定数组大小构造
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
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);
}
初始化默认大小为DEFAULT_INITIAL_CAPACITY=16,最大大小为MAXIMUM_CAPACITY=1 << 30,
put方法
当通过new创建hashmap对象时,并未创建数组,hashmap的创建属于懒加载,只有在第一次put元素的时候,才会完成所有创建。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0) //第一次创建 table==null,进入resize
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); //未产生hash冲突,则直接在索引对应位置放入元素
else {
Node<K,V> e; K k;
if (p.hash == hash && //put相同key,即产生hash冲突时
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode) //否则key不同hash相同,检查是否树化
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else { //没有树化,则进行链式处理hash冲突
for (int binCount = 0; ; ++binCount) { //遍历链表,添加节点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) { //将map中的元素转移到扩容后的map中
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode) //树化
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order 复制过程中出现hash冲突,将oldTab中,处理为链式的链表进行拆分, 分为高位链表和低位链表
Node<K,V> loHead = null, loTail = null; //低位链表 在新表中的索引同旧表中索引一致 j
Node<K,V> hiHead = null, hiTail = null; //高位链表 在新表中的索引为在旧表中的索引值+旧表的长度 j + oldCap
Node<K,V> next;
do {
next = e.next; //(&运算:两个同时为1,结果为1,否则为0)
if ((e.hash & oldCap) == 0) { //按位拆分,原理: 在一个桶中的节点,其hash值后四位是一致的,而第五位值是0或1(0做低位,1做高位)
if (loTail == null) //原因在于hash算法,在put元素时,寻址计算index索引时,计算方式为 :表长度-1 & hash值
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
创建过程图示
参考博客:
https://blog.csdn.net/qq_40574571/article/details/97612100
https://blog.csdn.net/u010890358/article/details/80496144#%E6%89%A9%E5%AE%B9%E6%9C%BA%E5%88%B6%E6%A0%B8%E5%BF%83%E6%96%B9%E6%B3%95Node%3CK%2CV%3E%5B%5D%20resize()
https://blog.csdn.net/woshimaxiao1/article/details/83661464