HashMap源码(jdk 1.8)

289 阅读23分钟

JDK1.8中,它可以看作是数组(Node<K,V>[] table)和链表结合组成的复合结构,数组被分为一个个桶(bucket),通过哈希值决定了键值对在这个数组的寻址;哈希值相同的键值对,则以链表形式存储,你可以参考下面的示意图。这里需要注意的是,如果链表大小超过阈值(TREEIFY_THRESHOLD, 8),图中的链表就会被改造为树形结构。

1、JDK 1.8 HashMap涉及的数据结构

1.1、桶数组(bucket)

/**
 * The table, initialized on first use, and resized as
 * necessary. When allocated, length is always a power of two.
 * (We also tolerate length zero in some operations to allow
 * bootstrapping mechanics that are currently not needed.)
 */
transient Node<K,V>[] table;

bin 可以翻译为桶,Node<K, V> table中每个位置可以成为一个bin

1.2、数组元素Node<K,V>实现了Entry接口

/**
 * Basic hash bin node, used for most entries.  (See below for
 * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
 */
 // 单向链表,实现了Map.Entry接口
static class Node<K,V> implements Map.Entry<K,V> {
	final int hash;
	final K key;
	V value;
	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; }

	public final int hashCode() {
		return Objects.hashCode(key) ^ Objects.hashCode(value);
	}

	public final V setValue(V newValue) {
		V oldValue = value;
		value = newValue;
		return oldValue;
	}

	// 重写了equals, 判断两个Node是否相等, 若key和value都相等,返回true。可以与自身比较为true
	public final boolean equals(Object o) {
		if (o == this)
			return true;
		if (o instanceof Map.Entry) {
			Map.Entry<?,?> e = (Map.Entry<?,?>)o;
			if (Objects.equals(key, e.getKey()) &&
				Objects.equals(value, e.getValue()))
				return true;
		}
		return false;
	}
}

1.3、红黑树

/**
 * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
 * extends Node) so can be used as extension of either regular or
 * linked node.
 */
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
	TreeNode<K,V> parent;  // red-black tree links
	TreeNode<K,V> left;
	TreeNode<K,V> right;
	TreeNode<K,V> prev;    // needed to unlink next upon deletion
	boolean red;
	TreeNode(int hash, K key, V val, Node<K,V> next) {
		super(hash, key, val, next);
	}

	/**
	 * Returns root of tree containing this node.
	 */
	 // 返回当前节点的根节点
	final TreeNode<K,V> root() {
		for (TreeNode<K,V> r = this, p;;) {
			if ((p = r.parent) == null)
				return r;
			r = p;
		}
	}
	
	……省略部分代码
}

2、HashMap中的关键属性

为什么需要使用加载因子,为什么需要扩容呢?

HashMap的底层是哈希表,是存储键值对的结构类型,它需要通过一定的计算才可以确定数据在哈希表中的存储位置

  • 如果空间利用率高,那么经过的哈希算法计算存储位置的时候,会发现很多存储位置已经有数据了(哈希冲突);
  • 如果为了避免发生哈希冲突,增大数组容量,就会导致空间利用率不高。

而加载因子就是表示Hash表中元素的填满程度。

如果一直不进行扩容的话,链表就会越来越长,这样查找的效率很低,因为链表的长度很大(当然最新版本使用了红黑树后会改进很多),扩容之后,将原来链表数组的每一个链表分成奇偶两个子链表分别挂在新链表数组的散列位置,这样就减少了每个链表的长度,增加查找效率

/**
 * The default initial capacity - MUST be a power of two.
 * 默认初始容量为16,必须是2的幂
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 * 最大容量,如果构造函数使用参数隐式指定了更高的值,则使用该容量。
 */
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
 * The load factor used when none specified in constructor.
 * 构造函数未指定时使用的默认负载因子
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 * 桶的树化阈值:即 链表转成红黑树的阈值,在存储数据时,当链表长度 > 该值时,则将链表转换成红黑树
 */
static final int TREEIFY_THRESHOLD = 8;
/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 * 桶的链表还原阈值:即 红黑树转为链表的阈值,当在扩容(resize())时(此时HashMap的数据存储位置会重新计算),在重新计算存储位置后,当原有的红黑树内数量 < 6时,则将 红黑树转换成链表
 */
static final int UNTREEIFY_THRESHOLD = 6;
/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 * 最小树形化容量阈值:即 当哈希表中的容量(数组的长度,而不是HashMap中键值对个数) > 该值时,才允许树形化链表 (即 将链表 转换成红黑树)
 * 否则,若桶内元素太多时,则直接扩容,而不是树形化
 * 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
 */
static final int MIN_TREEIFY_CAPACITY = 64;
/**
 * The load factor for the hash table.
 * hash表的负载因子
 * @serial
 */
final float loadFactor;
/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 * 这个值记录了HashMap结构修改次数,是指那些更改了HashMap键值对的数量或以其他方式修改其内部结构(例如,rehash)。此字段用于在使用迭代器迭代HashMap快速失败。(请参见ConcurrentModificationException)。
 */
transient int modCount;

modCount在HashMap中使用如下

abstract class HashIterator {
	Node<K,V> next;        // next entry to return
	Node<K,V> current;     // current entry
	int expectedModCount;  // for fast-fail
	int index;             // current slot

	HashIterator() {
		// 赋值给了期望的修改次数
		expectedModCount = modCount;
		Node<K,V>[] t = table;
		current = next = null;
		index = 0;
		if (t != null && size > 0) { // advance to first entry
			do {} while (index < t.length && (next = t[index++]) == null);
		}
	}

	public final boolean hasNext() {
		return next != null;
	}

	// 查询下一个节点
	final Node<K,V> nextNode() {
		Node<K,V>[] t;
		Node<K,V> e = next;
		// 发现修改次数和期望的不一样,也就是有别的线程对HashMap对象修改,直接抛出异常,快速失败
		if (modCount != expectedModCount)
			throw new ConcurrentModificationException();
		if (e == null)
			throw new NoSuchElementException();
		if ((next = (current = e).next) == null && (t = table) != null) {
			do {} while (index < t.length && (next = t[index++]) == null);
		}
		return e;
	}

	public final void remove() {
		Node<K,V> p = current;
		if (p == null)
			throw new IllegalStateException();
		if (modCount != expectedModCount)
			throw new ConcurrentModificationException();
		current = null;
		K key = p.key;
		removeNode(hash(key), key, null, false, false);
		expectedModCount = modCount;
	}
}

在ArrayList、LinkedList等内部增、删、改中都有使用modCount,字面意思就是修改次数,为什么要记录修改次数呢?

modCount 顾名思义就是修改次数,对HashMap内容的修改都将增加这个值,modeCount是申明为volatile,保证了线程间可见。这些使用了modCount属性的都是线程不安全的,从上面HashMap中HashIterator代码可以看出一个迭代器初始的时候会赋予它调用这个迭代器的对象的mCount,如何在迭代器遍历的过程中,一旦发现这个对象的modcount和迭代器中存储的modcount不一样那就抛异常,每次调用对象的next()方法的时候都会调用checkForComodification()方法进行一次检验,checkForComodification()方法中做的工作就是比较expectedModCount 和modCount的值是否相等,如果不相等,就认为还有其他对象正在对当前的List进行操作,那个就会抛出ConcurrentModificationException异常,这就是fail-fast策略。

/**
 * The next size value at which to resize (capacity * load factor).
 * 当HashMap的size大于threshold时会执行resize操作。 threshold = capacity * load factor
 * @serial
 */
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
// 此外,如果尚未分配HashMap桶数组,则此字段为初始数组容量,或零表示DEFAULT_INITIAL_CAPACITY
int threshold;
capacity
capacity译为容量。capacity就是指HashMap中桶的数量。默认值为16。一般第一次扩容时会扩容到64,之后好像是2倍。总之,容量都是2的幂。

final int capacity() {
	return (table != null) ? table.length :
		(threshold > 0) ? threshold :
		DEFAULT_INITIAL_CAPACITY;
}

3、HashMap 构造方法

3.1、无参构造方法

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 * 无参构造方法,使用默认初始容量(16)和默认的负载因子(0.75)
 */
public HashMap() {
	this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

3.2、一个初始容量的构造方法

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 * 构造方法指定了初始容量和默认的负载因子(0.75)
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
	this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

3.3、有两个参数的构造方法HashMap(int initialCapacity, float loadFactor)

参数:initialCapacity 初始容量

参数:loadFactor 负载因子

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 * 指定初始容量和负载因子构造一个空的HashMap
 *
 * @param  initialCapacity the initial capacity 初始容量
 * @param  loadFactor      the load factor 负载因子
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
public HashMap(int initialCapacity, float loadFactor) {
	// 初始容量如果小于0抛出异常
	if (initialCapacity < 0)
		throw new IllegalArgumentException("Illegal initial capacity: " +
										   initialCapacity);
	// 如果初始容量大于最大容量,指定初始容量为最大容量(1<<30)
	if (initialCapacity > MAXIMUM_CAPACITY)
		initialCapacity = MAXIMUM_CAPACITY;
	// 如果负载因子小于0或者不是数字抛出异常
	if (loadFactor <= 0 || Float.isNaN(loadFactor))
		throw new IllegalArgumentException("Illegal load factor: " +
										   loadFactor);
	this.loadFactor = loadFactor;
	// 计算出不小于initialCapacity的最小的2的幂的结果,并赋给成员变量threshold
	this.threshold = tableSizeFor(initialCapacity);
}

tableSizeFor()源码分析

/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
	// 容量减1,为了防止初始化容量已经是2的幂的情况,最后有+1运算
	int n = cap - 1;
	// 将n无符号右移一位再与n做或操作
	n |= n >>> 1;
	// 将n无符号右移两位再与n做或操作
	n |= n >>> 2;
	// 将n无符号右移四位再与n做或操作
	n |= n >>> 4;
	// 将n无符号右移八位再与n做或操作
	n |= n >>> 8;
	// 将n无符号右移十六位再与n做或操作
	n |= n >>> 16;
	// 如果入参cap为小于或等于0的数,那么经过cap-1之后n为负数,n经过无符号右移和或操作后仍未负数,所以如果n<0,则返回1;如果n大于或等于最大容量,则返回最大容量;否则返回n+1
	return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

详解如下:

如果n = 0(经过了cap-1之后),则经过后面的几次无符号右移依然是0,最后返回的capacity是1(最后有个n+1的操作)

这里只讨论n不等于0的情况。

第一次右移

n |= n >> 1;

由于n不等于0,则n的二进制表示中总会有一bit为1,这时考虑最高位的1。通过无符号右移1位,则将最高位的1右移了1位,再做或操作,使得n的二进制表示中与最高位的1紧邻的右边一位也为1,如000011xxxxxx。

第二次右移

n |= n >>> 2;

注意,这个n已经经过了n |= n >>> 1; 操作。假设此时n为000011xxxxxx ,则n无符号右移两位,会将最高位两个连续的1右移两位,然后再与原来的n做或操作,这样n的二进制表示的高位中会有4个连续的1。如00001111xxxxxx 。

第三次右移

n |= n >>> 4;

这次把已经有的高位中的连续的4个1,右移4位,再做或操作,这样n的二进制表示的高位中会有8个连续的1。如00001111 1111xxxxxx 。

以此类推

注意,容量最大也就是32bit的正数,因此最后n |= n >>> 16; ,最多也就32个1,但是这时已经大于了MAXIMUM_CAPACITY ,所以取值到MAXIMUM_CAPACITY 注意,得到的这个capacity却被赋值给了threshold。

this.threshold = tableSizeFor(initialCapacity);

开始以为这个是个Bug,感觉应该这么写:

this.threshold = tableSizeFor(initialCapacity) * this.loadFactor;

这样才符合threshold的意思(当HashMap的size到达threshold这个阈值时会扩容)。 但是,请注意,在构造方法中,并没有对table这个成员变量进行初始化,table的初始化被推迟到了put方法中,在put方法中会对threshold重新计算。

3.4、有一个Map类型的参数的构造方法

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 * 根据传入的指定的Map参数去初始化一个新的HashMap,该HashMap拥有着和原Map中相同的键值对。新的HashMap使用默认负载因子(0.75f),和足够的容量(能容纳原来指定的Map键值对的容量)
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
	this.loadFactor = DEFAULT_LOAD_FACTOR;
	putMapEntries(m, false);
}

我们看下putMapEntries()方法,这个方法调用了HashMap的resize()扩容方法和putVal()存入数据方法,源码如下:

/**
 * Implements Map.putAll and Map constructor.
 *
 * @param m the map
 * @param evict false when initially constructing this map, else
 * true (relayed to method afterNodeInsertion).
 */
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
	// 定义一个s,大小等于map的大小,这个未做非空判断,可能抛出空指针异常
	int s = m.size();
	// 如果map键值对个数大于0
	if (s > 0) {
		// 如果当前的HashMap的table为空
		if (table == null) { // pre-size
			// 计算HashMap的最小需要的容量
			float ft = ((float)s / loadFactor) + 1.0F;
			// 如果该容量大于最大容量,则使用最大容量
			int t = ((ft < (float)MAXIMUM_CAPACITY) ?
					 (int)ft : MAXIMUM_CAPACITY);
			// 如果容量大于threshold,则对对容量计算,取大于该容量的最小的2的幂的值, 并赋给threshold,作为HashMap的容量。tableSizeFor()方法讲解在上面
			if (t > threshold)
				threshold = tableSizeFor(t);
		}
		// 如果table不为空,即HashMap中已经有了数据,判断Map的大小是否超过了HashMap的阈值
		else if (s > threshold)
			// 如果超过阈值,则需要对HashMap进行扩容
			resize();
		// 对Map的EntrySet进行遍历
		for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
			K key = e.getKey();
			V value = e.getValue();
			// 调用HashMap的put方法的具体实现方法来对数据进行存放。
			putVal(hash(key), key, value, false, evict);
		}
	}
}

4、hashMap主要方法

4.1、get(Object key) 获取数据

/**
 * Returns the value to which the specified key is mapped,
 * or {@code null} if this map contains no mapping for the key.
 *
 * <p>More formally, if this map contains a mapping from a key
 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 * key.equals(k))}, then this method returns {@code v}; otherwise
 * it returns {@code null}.  (There can be at most one such mapping.)
 *
 * <p>A return value of {@code null} does not <i>necessarily</i>
 * indicate that the map contains no mapping for the key; it's also
 * possible that the map explicitly maps the key to {@code null}.
 * The {@link #containsKey containsKey} operation may be used to
 * distinguish these two cases.
 * 返回指定键映射到的值,或{@code null}(如果没有对应的key)。更正式的说法是,如果此map包含一个key(@code k)到value(@code v)的键值对
 * ,例如{@code(key==null ? k==null : key.equals(k))},则此方法返回{@code v};除此以外,它返回{@code null}。 (最多可以有一个这样的键值对。)
 * 
 * 返回值value{@code null}不一定表示该map不包含该key的键值对;也可能是该map可能会将key显式映射到null{@code null}。
 * {@link #containsKey containsKey}操作可用于区分这两种情况。
 *
 * @see #put(Object, Object)
 */
public V get(Object key) {
	Node<K,V> e;
	return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
 * Implements Map.get and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
	Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
	// 如果table(桶)数组不为空(map中有数据) 且 改hash对应数组的位置的元素(该位置第一个元素)不为空。(n - 1) & hash用来计算key在数组中的位置
	if ((tab = table) != null && (n = tab.length) > 0 &&
		(first = tab[(n - 1) & hash]) != null) {
		// 检查第一个Node是不是要找的Node,判断条件是hash值要相同,key值要相同(== 或者 equals)
		if (first.hash == hash && // always check first node
			((k = first.key) == key || (key != null && key.equals(k))))
			return first;
		// 检查第一个元素后面的Node
		if ((e = first.next) != null) {
			// 如果是树节点,通过getTreeNode(hash, key)直接查询返回
			if (first instanceof TreeNode)
				return ((TreeNode<K,V>)first).getTreeNode(hash, key);
			// 否则在链表上不断遍历后面的Node
			do {
				if (e.hash == hash &&
					((k = e.key) == key || (key != null && key.equals(k))))
					return e;
			} while ((e = e.next) != null);
		}
	}
	return null;
}

4.2、put(K key, V value)

4.2.1、put

/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 * 在这个map中将key和value关联。如果这个map已经包含了这个key的键值对,则旧的value会被替换。
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 * @return the previous value associated with <tt>key</tt>, or
 *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 *         (A <tt>null</tt> return can also indicate that the map
 *         previously associated <tt>null</tt> with <tt>key</tt>.)
 * 返回之前的和这个key关联的value,如果没有和这个key关联的键值对则返回null。null也可能表示之前这个key关联的value就是null。
 */
public V put(K key, V value) {
	return putVal(hash(key), key, value, false, true);
}

看下hash方法

static final int hash(Object key) {
	int h;
	return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

为什么要无符号右移16位后做异或运算, 看下图 将h无符号右移16为相当于将高区16位移动到了低区的16位,再与原hashcode做异或运算,可以将高低位二进制特征混合起来

从上文可知高区的16位与原hashcode相比没有发生变化,低区的16位发生了变化 ,我们可知通过上面(h = key.hashCode()) ^ (h >>> 16)进行运算可以把高区与低区的二进制特征混合到低区,那么为什么要这么做呢?

我们都知道重新计算出的新哈希值在后面将会参与hashmap中数组槽位的计算,计算公式:(n - 1) & hash,假如这时数组槽位有16个,则槽位计算如下: 仔细观察上文不难发现,高区的16位很有可能会被数组槽位数的二进制码锁屏蔽,如果我们不做刚才移位异或运算,那么在计算槽位时将丢失高区特征,也就是增加了hash碰撞的几率。

使用异或运算的原因

可以看下前面get方法中计算键值对在map内部数组位置的方法

tab[(n - 1) & hash]

hash % n == (n - 1) & hash 其中 n 是数组的长度。其实该算法的结果和模运算(当n是2的指数时候)的结果是相同的。但是,对于现代的处理器来说,除法和求余数(模运算)是最慢的动作。另外异或运算能更好的保留各部分的特征,如果采用&运算计算出来的值会向0靠拢,采用|运算计算出来的值会向1靠拢。

HashMap 的容量为什么建议是 2的幂次方?

只有是2的幂次方才能让hash值均匀的分布在桶中(数组)

假设我们的数组长度是10,还是上面的公式: 1010 & 101010100101001001000 结果:1000 = 8 1010 & 101000101101001001001 结果:1000 = 8 1010 & 101010101101101001010 结果: 1010 = 10 1010 & 101100100111001101100 结果: 1000 = 8

这种散列结果,会导致这些不同的key值全部进入到相同的插槽中,形成链表,性能急剧下降。我们一定要保证 & 中的二进制位全为 1,才能最大限度的利用 hash 值,并更好的散列,只有全是1 ,才能有更多的散列结果。如果是 1010,有的散列结果是永远都不会出现的,比如 0111,0101,1111,1110…,只要 & 之前的数有 0, 对应的 1 肯定就不会出现(因为只有都是1才会为1)。大大限制了散列的范围。

另外,map发生扩容的时候,需要重新计算所有key的hash值放到新的hash桶上面,这个时候差别的更大了,扩容后数组大小n是原来两倍,假设原来n为16,新的n - 1 = 31(11111)计算之后就比原来的n - 1 = 15(1111)多了一个最高位是1,这样扩容后原来数组只有两种情况,一种在原来位置,一种是原来坐标+原来数组的容量。

4.2.2、putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)

/**
 * 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未初始化或者长度为0,进行扩容
	if ((tab = table) == null || (n = tab.length) == 0)
		n = (tab = resize()).length;
	// (n - 1) & hash 确定元素存放在哪个桶中,p被赋值为桶中第一个元素,如果p为空(桶为空),新生成结点放入桶中(HashMap中Node<K,V>[] table数组的对应位置)
	if ((p = tab[i = (n - 1) & hash]) == null)
		tab[i] = newNode(hash, key, value, null);
	// 桶中存在元素
	else {
		Node<K,V> e; K k;
		// 比较桶中第一个元素, 如果(数组中的结点)的hash值相等且key相等(== 或者 equals),k被赋值为p.key, e被赋值为p
		if (p.hash == hash &&
			((k = p.key) == key || (key != null && key.equals(k))))
			// 将第一个元素赋值给e,用e来记录
			e = p;
		// key不相等(hash值不相等 或者 key不相等);为红黑树结点
		else if (p instanceof TreeNode)
			// 生成新的树节点放入红黑树中并赋值给e
			e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
		else {
			// 遍历,在链表最末尾插入节点
			for (int binCount = 0; ; ++binCount) {
				// e被赋值为p的下一个节点,判断e(下一个节点)是否为null(为null的时候到达尾部)
				if ((e = p.next) == null) {
					// 创建一个新的节点,放到p的下一个节点(也就是放到尾部)
					p.next = newNode(hash, key, value, null);
					// 判断这个桶中Node是否到达TREEIFY_THRESHOLD阈值(默认为8),到达就转化为红黑树(下面treeifyBin(tab, hash)方法中还有具体是扩容还是树化逻辑)
					if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
						// treeifyBin首先判断当前hashMap的长度,如果不足64,只进行resize,扩容table,如果达到64,那么将冲突的存储结构为红黑树
						treeifyBin(tab, hash);
					break;
				}
				// 同上面,找到相同的key(hash值相等并且key相等(== 或 equals)), 直接跳出循环
				if (e.hash == hash &&
					((k = e.key) == key || (key != null && key.equals(k))))
					break;
				// e为p.next,这里把e重新赋值给p就是循着链表头往尾部循环
				p = e;
			}
		}
		// e不为null表示存在相同的key(hash值相等并且key相等(== 或 equals))
		if (e != null) { // existing mapping for key
			V oldValue = e.value;
			// 是否需要替换旧的value
			if (!onlyIfAbsent || oldValue == null)
				e.value = value;
			// 访问后回调
			afterNodeAccess(e);
			// 返回旧value
			return oldValue;
		}
	}
	// 修改次数+1,modCount用处请参考前面modCount作用(多线程操作同一个HashMap时候快速失败)
	++modCount;
	// 元素个数大于threshold时候扩容
	if (++size > threshold)
		resize();
	// 插入后回调
	afterNodeInsertion(evict);
	return null;
}

4.3、HashMap的扩容机制resize()

构造hash表时,如果不指明初始大小,默认大小为16(即Node数组大小16),如果Node[]数组中的元素达到(loadFactor*capacity(Node.length))重新调整HashMap大小 变为原来2倍大小,扩容很耗时

/**
 * 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.
 * 初始化或者表容量翻倍。如果表为null,则根据存放在threshold变量中的初始化capacity的值来分配table内存(这个注释说的很清楚,在实例化HashMap时,
 * capacity其实是存放在了成员变量threshold中,注意,HashMap中没有capacity这个成员变量)。如果表不为null,由于我们使用2的幂来扩容,
 * 则每个bin元素要么还是在原来的bucket中,要么在原来的下标位置+原来的表的容量计算出来的下标的位置中。
 *
 * 此方法功能:初始化或扩容
 *
 * @return the table
 */
final Node<K,V>[] resize() {
	Node<K,V>[] oldTab = table;
	// 旧的capacity,为null是实例化HashMap时候没有初始化Node[]数组
	int oldCap = (oldTab == null) ? 0 : oldTab.length;
	int oldThr = threshold;
	// 新的容量值,新的扩容阈值
	int newCap, newThr = 0;
	// 旧的容量不为空,也就是HashMap不为空
	if (oldCap > 0) {
		// 如果大于最大容量,设置阈值为Integer.MAX_VALUE, 返回旧的Node[]数组
		if (oldCap >= MAXIMUM_CAPACITY) {
			threshold = Integer.MAX_VALUE;
			return oldTab;
		}
		// 如果(当前容量*2<最大容量&&当前容量>=默认初始化容量(16)), 并将将原容量值<<1(相当于*2)赋值给 newCap
		else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
				 oldCap >= DEFAULT_INITIAL_CAPACITY)
			newThr = oldThr << 1; // double threshold
	}
	// 进入此if证明创建map时用的带参构造:public HashMap(int initialCapacity)或 public HashMap(int initialCapacity, float loadFactor)
    // 注:带参的构造中initialCapacity(初始容量值)不管是输入几都会通过 “this.threshold = tableSizeFor(initialCapacity);”
	// 此方法计算出接近initialCapacity参数的2^n来作为初始化容量(初始化容量==oldThr)
	else if (oldThr > 0) // initial capacity was placed in threshold
		newCap = oldThr;
	else {               // zero initial threshold signifies using defaults
		// 进入此证明创建map时用的无参构造
		newCap = DEFAULT_INITIAL_CAPACITY;
		newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
	}
	if (newThr == 0) {
		// 进入此if有两种可能
        // 第一种:进入此“if (oldCap > 0)”中且不满足该if中的两个if
        // 第二种:进入这个“else if (oldThr > 0)”
		
		// 分析:进入此if证明该map在创建时用的带参构造,如果是第一种情况就说明是进行扩容(第二个else if中newCap = oldCap << 1)且oldCap(旧容量)小于16,如果是第二种说明是第一次put
		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;
	// 如果“oldTab != null”说明是扩容,否则直接返回newTab
	if (oldTab != null) {
		// 遍历旧的Node[]数组
		for (int j = 0; j < oldCap; ++j) {
			Node<K,V> e;
			// 数组中第一个Node复制给e
			if ((e = oldTab[j]) != null) {
				oldTab[j] = null;
				// 如果下一个节点是null说明这个桶中只有一个Node
				if (e.next == null)
					// 计算扩容后存放的位置并赋值
					newTab[e.hash & (newCap - 1)] = e;
				// 如果是TreeNode(转化为红黑树了)
				else if (e instanceof TreeNode)
					// todo
					((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
				else { // preserve order
					// 能进入这里说明不是红黑树,也不止一个节点,那么就是链表
					// 接受扩容后在原来位置的节点
					Node<K,V> loHead = null, loTail = null;
					// 接受扩容后放在放在“j + oldCap”(当前位置索引+原容量的值)(请参考hashMap get方法关于hash算法的分析)
					Node<K,V> hiHead = null, hiTail = null;
					Node<K,V> next;
					/**
					 * 需要注意的是这个if else把这个桶中链表上的Node分为了两组,一组在原来的位置,一组在e.hash & (newCap - 1)下标的位置
					 */
					do {
						/**
						 *	这部分代码分析见下图
						 */
						// 便于循环往后遍历,且保证了顺序
						next = e.next;
						// 由于oldCap为2的幂次方,最高位为1,正常计算key在Node[]位置时候用e.hash & (oldCap - 1), 而这里是扩容了变为原来2倍
						// ,也就是newCap比oldCap最高位多一个1,此时如果(e.hash & oldCap) == 0说明e.hash & (newCap - 1) = e.hash & (oldCap - 1)也就是在原来的下标位置的数组中
						// , 因为oldCap和newCap(2*oldCap) - 1最高位是一样的且说明多出的一个hash值为0。
						if ((e.hash & oldCap) == 0) {
							// 在这个位置的只有第一个Node会进入if
							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;
}/**
 * 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.
 * 初始化或者表容量翻倍。如果表为null,则根据存放在threshold变量中的初始化capacity的值来分配table内存(这个注释说的很清楚,在实例化HashMap时,
 * capacity其实是存放在了成员变量threshold中,注意,HashMap中没有capacity这个成员变量)。如果表不为null,由于我们使用2的幂来扩容,
 * 则每个bin元素要么还是在原来的bucket中,要么在原来的下标位置+原来的表的容量计算出来的下标的位置中。
 *
 * 此方法功能:初始化或扩容
 *
 * @return the table
 */
final Node<K,V>[] resize() {
	Node<K,V>[] oldTab = table;
	// 旧的capacity,为null是实例化HashMap时候没有初始化Node[]数组
	int oldCap = (oldTab == null) ? 0 : oldTab.length;
	int oldThr = threshold;
	// 新的容量值,新的扩容阈值
	int newCap, newThr = 0;
	// 旧的容量不为空,也就是HashMap不为空
	if (oldCap > 0) {
		// 如果大于最大容量,设置阈值为Integer.MAX_VALUE, 返回旧的Node[]数组
		if (oldCap >= MAXIMUM_CAPACITY) {
			threshold = Integer.MAX_VALUE;
			return oldTab;
		}
		// 如果(当前容量*2<最大容量&&当前容量>=默认初始化容量(16)), 并将将原容量值<<1(相当于*2)赋值给 newCap
		else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
				 oldCap >= DEFAULT_INITIAL_CAPACITY)
			newThr = oldThr << 1; // double threshold
	}
	// 进入此if证明创建map时用的带参构造:public HashMap(int initialCapacity)或 public HashMap(int initialCapacity, float loadFactor)
    // 注:带参的构造中initialCapacity(初始容量值)不管是输入几都会通过 “this.threshold = tableSizeFor(initialCapacity);”
	// 此方法计算出接近initialCapacity参数的2^n来作为初始化容量(初始化容量==oldThr)
	else if (oldThr > 0) // initial capacity was placed in threshold
		newCap = oldThr;
	else {               // zero initial threshold signifies using defaults
		// 进入此证明创建map时用的无参构造
		newCap = DEFAULT_INITIAL_CAPACITY;
		newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
	}
	if (newThr == 0) {
		// 进入此if有两种可能
        // 第一种:进入此“if (oldCap > 0)”中且不满足该if中的两个if
        // 第二种:进入这个“else if (oldThr > 0)”
		
		// 分析:进入此if证明该map在创建时用的带参构造,如果是第一种情况就说明是进行扩容(第二个else if中newCap = oldCap << 1)且oldCap(旧容量)小于16,如果是第二种说明是第一次put
		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;
	// 如果“oldTab != null”说明是扩容,否则直接返回newTab
	if (oldTab != null) {
		// 遍历旧的Node[]数组
		for (int j = 0; j < oldCap; ++j) {
			Node<K,V> e;
			// 数组中第一个Node复制给e
			if ((e = oldTab[j]) != null) {
				oldTab[j] = null;
				// 如果下一个节点是null说明这个桶中只有一个Node
				if (e.next == null)
					// 计算扩容后存放的位置并赋值
					newTab[e.hash & (newCap - 1)] = e;
				// 如果是TreeNode(转化为红黑树了)
				else if (e instanceof TreeNode)
					// todo
					((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
				else { // preserve order
					// 能进入这里说明不是红黑树,也不止一个节点,那么就是链表
					// 接受扩容后在原来位置的节点
					Node<K,V> loHead = null, loTail = null;
					// 接受扩容后放在放在“j + oldCap”(当前位置索引+原容量的值)(请参考hashMap get方法关于hash算法的分析)
					Node<K,V> hiHead = null, hiTail = null;
					Node<K,V> next;
					/**
					 * 需要注意的是这个if else把这个桶中链表上的Node分为了两组,一组在原来的位置,一组在e.hash & (newCap - 1)下标的位置
					 */
					do {
						/**
						 *	这部分代码分析见下图
						 */
						// 便于循环往后遍历,且保证了顺序
						next = e.next;
						// 由于oldCap为2的幂次方,最高位为1,正常计算key在Node[]位置时候用e.hash & (oldCap - 1), 而这里是扩容了变为原来2倍
						// ,也就是newCap比oldCap最高位多一个1,此时如果(e.hash & oldCap) == 0说明e.hash & (newCap - 1) = e.hash & (oldCap - 1)也就是在原来的下标位置的数组中
						// , 因为oldCap和newCap(2*oldCap) - 1最高位是一样的且说明多出的一个hash值为0。
						if ((e.hash & oldCap) == 0) {
							// 在这个位置的只有第一个Node会进入if
							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;
}

参考:www.cnblogs.com/little-fly/… www.cnblogs.com/shianliang/… blog.csdn.net/v123411739/…