基于jdk1.8的HashMap源码学习笔记

时间:2024-04-02 18:03:25

作为一种最为常用的容器,同时也是效率比较高的容器,HashMap当之无愧。所以自己这次jdk源码学习,就从HashMap开始吧,当然水平有限,有不正确的地方,欢迎指正,促进共同学习进步,就是喜欢程序员这种开源精神。(好吧,第一篇博客有点紧张)

一. HashMap结构

HashMap在jdk1.6版本采用数组+链表的存储方式,但是到1.8版本时采用了数组+链表/红黑树的方式进行存储,有效的提高了查找时间,解决冲突。这里有一篇博客写的非常好,HashMap的结构图也画的非常清楚,鼎力推荐一下杭州Mark的HashMap源码分析。虽然是基于jdk1.6的,但是换成jdk1.8,只要链表长度大于门限时,换成红黑树就好了, 我就不具体解释HashMap的具体结构了。

二.HashMap 定义

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

继承自AbstractMap,这是一个抽象类,定义了并且实现了Map接口的基本行为,但是基本上HashMap都对其进行了重写覆盖,采用了自己更高效的方式。AbstractMap是我们自己编写Map时,可以用到的基类。(好吧,来自JAVA编程思想,还没有自己写过Map)

实现了Map接口,这里其实有一个疑问,为什么在AbstractMap中已经明显实现Map接口的情况下,还要显著在实现Map接口?这种设计方式的原因?
      其余都是标记接口。

三.重要的field属性

//默认的初始化数组大小为16,为啥不直接写16(jdk1.6是这么干的)啊?confused
//这里必须是2的整数幂,
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4
//最大存储容量
static final int MAXIMUM_CAPACITY = 1 << 30
//默认装载因子,我理解的就是所占最大百分比,即当超过75%时,就需要扩容了
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//这是jdk1.8新加的,这是链表的最大长度,当大于这个长度时,就会将链表转成红黑树
static final int TREEIFY_THRESHOLD = 8; //table就是存储Node 的数组,就是hash表中的桶位,后面会重点介绍Node
transient Node<K,V>[] table;
//实际存储的数量,则HashMap的size()方法,实际返回的就是这个值,isEmpty()也是判断该值是否为0
transient int size;
//HashMap每改变一次结构,不管是添加还是删除都会modCount+1,主要用来当迭代时,保持数据的一致性(不知道这么理解正确么?)
//因为每一次迭代,都会检查modCount是否改变是否一致,不一致就会抛出异常。这也是为什么迭代过程中,除了运用迭代器的remove()方法外,不能自己进行改变数据
//fast-fail机制
transient int modCount; //扩容的门限值,当大于这个值时,table数组要进行扩容,一般等于(cap*loadFactor)
int threshold;
//装载因子
final float loadFactor;

四.HashMap构造器

HashMap共有四种构造器,常用的有三种,主要分为无参构造器,应用默认的参数;指定初始化容量的构造器;将原有Map装进当前HashMap的构造器。

1.无参构造器

//这就是一个默认的方式,潜在的问题是初始容量16太小了,可能中间需要不断扩容的问题,会影响插入的效率,当看到后面resize()方法时,可以很明显的看到这个问题
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

2.含参包括装载因子,与容量

//可以指定初始容量,以及装载因子,但是感觉一般情况下指定装载因子意义不大
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)//这里就重新定义了扩容的门限
}

可以看到此时threshold被tableSizeFor()方法重新计算了,那我们研究一下tableSizeFor方法

//tableSizeFor的功能主要是用来保证容量应该大于cap,且为2的整数幂,但是这段代码没有完全看懂
//我理解了一下就是将最高位依次跟后面的进行或运算,将低位全变成1,最后在n+1,从而变成2的整数幂
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;
}

不得不说写源码的都是追求完美的大神,下面是jdk1.6的实现方式,就是简单的循环,可以看到采用位运算后效率明显提高了

int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;

这里可能还有一个疑问,明明给的是初始容量,为什么要计算门限,而不是容量呢?其实这也是jdk1.8的改变,它将table的初始化放入了resize()中,而且压根就没有capacity这个属性,所以这里只能重新计算threshold,而resize()后面就会根据threshold来重新计算capacity,来进行table数组的初始化,然后在重新按照装载因子计算threshold,有点绕,后面看resize()源码就清楚了。

3.仅仅指定容量

//下面这种方式更好,所以当知道所要构建的数据容量大小时,最好直接指定大小,可以减除不停扩容的过程,大幅提高效率
public HashMap(int initialCapacity){
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

4.将已有Map放入当前map中

//这种方式是将已有Map中的元素放入当前HashMap中
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
//这里就是一个个取出m中的元素调用putVal,一个个放入table中的过程。
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
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);
}
}
}

五.重要的方法

1.Node 内部类

可以看到前面table就是Node数组,Node是什么?它是一个HashMap内部类(改名字了,jdk1.6就叫Entry),继承自 Map.Entry这个内部接口,它就是存储一对映射关系的最小单元,也就是说key,value实际存储在Node中。

//可以看出虽然这里不叫Entry这个广泛应用的名字了,但是与jdk1.6比,还是没有什么大的变化
//依然实现了Map.Entry这个内部接口,换汤没换药
//其实就是最基本的链表实现方式
static class Node<K,V> implements Map.Entry<K,V> {
//可以发现,HashMap的每个键值对就是靠这里实现的,并没有很高大上
//并且键应用了final修饰符,所以键是不可改变的!
final int hash;//这里这个一般保存键的hash值
final K key;
V value;
//next 应用于一个桶位中的链表结构,表示下一个节点键值对
Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
} public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
//键的hashcode与值的hashcode异或,得到hash值,并且这里应用的是最原始的hashCode计算方式,Objects
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
} public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
} public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
//键和值都eauals,才行,而且是Objects.equals,只能是同一对象
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}

2.put方法

//可以看到是调用的putVal的方法,并且计算了key的hash值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
// Computes key.hashCode() and spreads (XORs) higher bits of hash
/** to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
//这里可以看到key是有可能是null的,并且会在0桶位位置
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

这里hashCode的计算也进行了改进,取得key的hashcode后,高16位与低16位异或运算重新计算hash值。

下面重点看一下put方法实现的大拿,putVal方法。

/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//table 没有初始化
if ((tab = table) == null || (n = tab.length) == 0)
//可以看到table的初始化放在了这里,是通过resize来做的,后面会分析resize()
n = (tab = resize()).length; //这里就是HASH算法了,用来定位桶位的方式,可以看到是采用容量-1与键hash值进行与运算
//n-1,的原因就是n一定是一个2的整数幂,而(n - 1) & hash其实质就是n%hash,但是取余运算的效率明显不如位运算与
//并且(n - 1) & hash也能保证散列均匀,不会产生只有偶数位有值的现象
if ((p = tab[i = (n - 1) & hash]) == null)
//当这里是空桶位时,就直接构造新的Node节点,将其放入桶位中
//newNode()方法,就是对new Node(,,,)的包装
//同时也可以看到Node中的hash值就是重新计算的hash(key)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//键hash值相等,键相等时,这里就是发现该键已经存在于Map中
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//当该桶位是红黑树结构时,则应该按照红黑树方式插入
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //当该桶位为链表结构时,进行链表的插入操作,但是当链表长度大于TREEIFY_THRESHOLD - 1,就要将链表转换成红黑树
else {
//这里binCount记录链表的长度
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;
}
}
//替换操作,onlyIfAbsent为false
//所以onlyIfAbsent,这个参数主要决定是否执行替换,当该键已经存在时,
//而下面的方法则是一种不替换的put方法,因为onlyIfAbsent为true
//这里其实只是为了给putIfAbsent方法提供支持,这也是jdk1.8新增的方法
// public V putIfAbsent(K key, V value) {
// return putVal(hash(key), key, value, true, true);
// }
//
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;
}

下面在看一下扩容方法resize(),jdk1.8的resize相比以往又多了一份使命,table初始化部分,也会在这里完成。

/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*/ 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
//这个是采用HashMap()这个方式构造容器时,可以看到就只是采用默认值就行初始化
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
            //这里可以看出门限与容量的关系,永远满足loadFactor这个装载因子
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//更新门限到threshold field
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//好吧,找它一圈终于找到table的初始化了
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//这里就是当原始table不为空时,要有一个搬家的过程,所以这里是最浪费效率的
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
//先释放,解脱它,而不是等着JVM自己收集,因为有可能导致根本没有被收集,因为原始引用还在
oldTab[j] = null;
//当该桶位链表长度为1时,
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
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
//这里又是一个理解不太清楚的地方了
//(e.hash & oldCap) == 0,应该是表示原hash值小于oldcap,则其桶位不变,链表还 是在原位置
//若>0,则表示原hash值大于该oldCap,则桶位变为j + oldCap
//从结果来看等效于e.hash & (newCap - 1),只是不知道为何这样计算
//而且与jdk1.6比,这里链表并没有被倒置,而jdk1.6中,每次扩容链表都会被倒置
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
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;
}

其实HashMap put方法中最重要的就是putVal和resize()这两个方法了,搞懂他们,就基本搞懂HashMap的存储方式了,因为get方法就是一个反向的过程。

putAll方法就easy了

public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}

3.get方法

get方法同样也是最常用的方法(不可能光存不取啊),可以看到通过getNode方法获得节点后,直接取出Node的value属性即可。

public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//这里就是hash算法查找的过程,可以看到与put方法是一致的
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//这里就是分成两种了一个是,红黑树查找
//一个是链表查找
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//值得注意的是当查找不到的时候是返回null的
return null;
}

相比于插入由于少了扩容的部分,get查找简化了很多,这里也能看到hash算法的精髓,快速定位查找功能,不需要遍历就能查找到。

//containsKey,查询是否存在某个键,getNode()大法好
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}

4.remove方法

//根据键,删除某一个节点,返回value值
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* Implements Map.remove and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//这里的node就是 所查找到的节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
//这里p保存的是父节点,因为这里涉及到链表删除的操作
p = e;
} while ((e = e.next) != null);
}
}
//这里可以看出matchValue这个参数的作用了
//当matchValue为false时(即这里我们remove方法所用的),直接短路后面的运算,进行删除操作,而不用关注value值是否相等或者equals
//而matchValue为true时,则只有在value值也符合时,才删除
//而jdk1.8也是给了重载方法,应用于当key键与value值同时匹配时,才进行删除操作
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
//movable这个参数竟然是应用在了树删除上,可以再看一看
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//表示该节点就是链表的头节点,则将子节点放进桶位
else if (node == p)
tab[index] = node.next;
//删除节点后节点,父节点的next重新连接
else
p.next = node.next;
//删除操作也是要记录进modCount的
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}

这里matchValue这个参数设置很巧妙,巧妙的解决了这个方法的重用问题,当然源码里还有很多很精巧的设计。

//这是jdk1.8新增的方法,可以看到只有matchValue改变成了true
//只有键和值都匹配才删除
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;

5.replace方法

似乎是jdk1.8新增的方法,但是有了前面的理解,这个方法自己写也能做出来。
      可以有两种方案,一种是采用putVal的方法,因为很明显putVal是能够替换的,但是这里就涉及到了size,和modCount这两个field的变化了,也是要注意的。

另一种是getNode得到节点,然后替换,所以采用了getNode这个方法。

//分为两种,一种是死切摆列的非要key和 value都匹配上,才换
//另一种就是键匹配就换
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}

可以看出jdk1.8考虑了更多的应用场景。

5.其他方法

/**
* Removes all of the mappings from this map.
* The map will be empty after this call returns.
*/
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
public int size() {
return size;
}
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty() {
return size == 0;
}

六.总结

通过分析HashMap源码,可以很好的领会Hash算法的实现原理,以及实现中的各种问题,同时对于链表的操作也是一个非常好的提高过程。

这里也发现,其实这次学习笔记,只是记录了最基本的增删改查,而红黑树,以及entryset,迭代器等等都还没有进行介绍,这也是留在后面有时间要重点介绍的。同时自己的Hash算法基础也要过过关了。

这是第一篇博客,是对自己学习过程的一个记录,也是一个督促。最后再感谢杭州.Mark的那篇博文,对自己分析HashMap有一个非常大的借鉴意义。