Java源码分析——HashMap

什么是哈希

哈希(Hash),也称散列,可将任意长度的的输入,通过某种映射规则变成固定长度的输出,这种映射规则称为哈希算法,得到的输出称为哈希值散列值

  • 从哈希值不能反向推导出原始数据
  • 相同的数据经过哈希算法会得到相同的哈希值
  • 由于哈希算法的原理是将输入空间的值映射到 hash 空间内,而 hash 空间较小,故一定会存在不同的输入得到相同的哈希值的现象,称为哈希冲突

HashMap 简介

  • HashMap 是 Map 接口基于哈希表的实现,此实现提供了所有可选的映射操作,并允许 null 作为值或键
  • HashMap 是非同步的(线程不安全)
  • HashMap 不保证映射的顺序
  • JDK1.8 之前 HashMap 由 数组 + 链表 组成(链表为了解决哈希冲突),而 JDK1.8 后由 数组 + 链表 + 红黑树 组成(链表长度大于 8 ,数组长度大于 64 时链表转化为红黑树,若仅仅链表长度大于 8 ,而数组长度不足,则会优先选择数组扩容)

HashMap 底层数据结构

HashMap 底层维护了一个 table 数组来存储键值对,并随着链表长度和红黑树节点数的变化,进行链表与红黑树的动态转换

对于 table 数组的元素类型,在 JDK1.8 之前为 Entry<K, V>,而 JDK1.8 后为 Node<K, V>

对于 table 数组的初始化,在 JDK1.8 之前,是在构造函数中进行的,而 JDK1.8 后,是在第一次调用 put 方法时进行的


Hashmap 核心属性

常量

/**
 * The default initial capacity - MUST be a power of two.
 * 默认容量,必须是 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.
 * 最大容量,必须是 2 的次幂
 */
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.
 * 树化阈值,当链表长度超过该阈值,且数组长度大于 MIN_TREEIFY_CAPACITY 时,转化为红黑树
 */
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.
 * 链化阈值,当红黑树节点个数低于该阈值时,转化为链表
 */
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.
 * 树化阈值,当数组长度超过该阈值,且链表长度超过 TREEIFY_THRESHOLD 时,转化为红黑树
 */
static final int MIN_TREEIFY_CAPACITY = 64;

成员变量

/* ---------------- Fields -------------- */

/**
 * 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;

/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 * 
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * The number of key-value mappings contained in this map.
 * 当前哈希表中元素个数
 */
transient int size;

/**
 * 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).
 * 当前哈希表结构修改次数(插入、删除操作)
 */
transient int modCount;

/**
 * The next size value at which to resize (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.)
int threshold;

/**
 * The load factor for the hash table.
 *
 * 负载因子,用于计算 threshold
 * threshold = capacity * loadFactor
 * @serial
 */
final float loadFactor;

HashMap 构造方法

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 *
 * @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) {
	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);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
	this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
	this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * 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>.
 *
 * @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);
}

对于两个参数的构造函数,首先进行参数校验,参数合法时将参数赋值到成员变量中,对于 threshold 的计算,调用 tableSizeFor() 方法进行

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);
}

tableSizeFor() 方法通过位运算,获取扩容阈值

/**
 * Returns a power of two size for the given target capacity.
 * 返回一个大于等于 cap 的数,且该数为 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;
}

其余构造方法较为简单,不再赘述


HashMap put() 方法

put() 方法调用 putVal() 方法,也就是说核心逻辑在 putVal() 方法中,对该方法的调用,传入了经过扰动函数 hash() 计算的 key 的哈希值

public V put(K key, V value) {
	return putVal(hash(key), key, value, false, true);
}

扰动函数 hash() ,首先获取 key 的 hashCode ,将该 hashCode 与该 hashCode 右移 16 位的结果进行异或,从而使得 32 位的结果中,低 16 位也蕴含了高 16 位的信息

因为当数组长度很小时,进行路由寻址计算时,如果不进行扰动计算,hashCode 的高 16 位不能参与运算,路由寻址只取最后几位的话,可能造成冲突严重

路由寻址公式:(h = key.hashCode()) ^ (h >>> 16) & (length - 1)

length 为 2 的次幂,故 length - 1 为全 1 的二进制数,& 运算相当于取模

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

putVal() 方法,传入参数如下

  • hash:key 的 hashCode 经扰动函数计算后得到的哈希值
  • key:键
  • value:值
  • onlyIfAbsent:为 true 则不更改现有的值
  • evict:为 false 表示 table 为创建状态
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
			   boolean evict) {
	//tab 引用当前 hashmap 的 table 数组(散列表)
	//p 表示当前的元素
	//n 表示 table 数组(散列表)的长度
	//i 表示路由寻址的结果(数组索引)
	HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
	//延迟初始化,第一次调用 putVal 时初始化 HashMap 中最耗费内存的散列表
	if ((tab = table) == null || (n = tab.length) == 0)
		n = (tab = resize()).length;
	//(n - 1) & hash 为路由寻址公式,若计算出的位置无数据,则直接填充
	if ((p = tab[i = (n - 1) & hash]) == null)
		tab[i] = newNode(hash, key, value, null);
	//若计算出的位置已存在数据
	else {
		//e 表示临时节点
		//k 表示临时 key
		HashMap.Node<K,V> e; K k;
		//若当前元素 p 与插入的元素,二者 key 一致,则用 e 记录 p,后续进行替换操作
		if (p.hash == hash &&
				((k = p.key) == key || (key != null && key.equals(k))))
			e = p;
		//若当前元素 p 已经树化
		else if (p instanceof TreeNode)
			e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
		//除此之外,只可能为链表节点
		else {
			//遍历链表,找到与待插入元素 key 一致的节点,若没有则通过尾插法插入到最后
			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;
				}
				//找到 key 一致的节点,用 e 记录,后续进行替换操作
				if (e.hash == hash &&
						((k = e.key) == key || (key != null && key.equals(k))))
					break;
				p = e;
			}
		}
		//要插入的 key 已存在,进行替换
		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;
}

HashMap 扩容原理

HashMap 默认容量为 16,随着数据的增加,链化情况加剧后,操作时间复杂度上升,性能降低,故需要进行自动扩容

HashMap 的扩容通过 resize() 方法实现,得到扩容后的 table 数组,并实现数据转移

resize() 方法同样适用于 table 初始化

final HashMap.Node<K,V>[] resize() {
		//oldTab 扩容前的散列表
		HashMap.Node<K,V>[] oldTab = table;
		//oldCap 扩容前的散列表长度
		int oldCap = (oldTab == null) ? 0 : oldTab.length;
		//oldThr 扩容前的散列表扩容阈值
		int oldThr = threshold;
		//newCap 扩容后的散列表长度
		//newThr 扩容后的散列表扩容阈值
		int newCap, newThr = 0;

		//计算 newCap 和 newThr 的值
		//散列表已初始化
		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
		}
		//oldCap == 0,散列表未初始化,但扩容阈值大于0,也就是通过有参构造方法构造 Hashmap 时,存在 2 的次幂的扩容阈值
		else if (oldThr > 0) // initial capacity was placed in threshold
			newCap = oldThr;
		//oldCap == 0 && oldThr == 0,散列表未初始化,通过无参构造方法构造 HashMap 时,采用默认的长度和扩容阈值
		else {               // zero initial threshold signifies using defaults
			newCap = DEFAULT_INITIAL_CAPACITY;
			newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
		}
		//上述未计算 newThr 时,通过 newCap 和 loadFactor 重新计算
		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"})
		HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
		table = newTab;
		//扩容前 table 不为 null,说明已经初始化,需要转移数据
		if (oldTab != null) {
			for (int j = 0; j < oldCap; ++j) {
				//e 当前节点
				HashMap.Node<K,V> e;
				//当前索引位置有数据,不确定是单个数据还是链表节点或红黑树根节点
				if ((e = oldTab[j]) != null) {
					//清空当前数据
					oldTab[j] = null;
					//若为单个数据(next 为 null 表示为单个数据)
					if (e.next == null)
						//计算新散列表索引,转移数据
						newTab[e.hash & (newCap - 1)] = e;
					//若为红黑树根节点
					else if (e instanceof HashMap.TreeNode)
						//
						((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
					//若为链表节点
					else { // preserve order
						//低位链表的头尾指针,存放在扩容之后的数组的索引位置,与当前数组的下标一致
						HashMap.Node<K,V> loHead = null, loTail = null;
						//高位链表的头尾指针,存放在扩容之后的数组的索引位置,为当前数组下表 + 扩容前的数组长度
						HashMap.Node<K,V> hiHead = null, hiTail = null;
						//临时节点
						HashMap.Node<K,V> next;
						do {
							next = e.next;
							//oldCap 为 2 的次幂,一定为 10000 这种形式
							//即检测 e.hash 的对应高位是否为0,以判断放入高位链表还是低位链表
							//这一段代码用于构建两个新链表,即高位链表和低位链表
							//对应高位为 0
							if ((e.hash & oldCap) == 0) {
								if (loTail == null)
									loHead = e;
								else
									loTail.next = e;
								loTail = e;
							}
							//对应高位为 1
							else {
								if (hiTail == null)
									hiHead = e;
								else
									hiTail.next = e;
								hiTail = e;
							}
							//
						} while ((e = next) != null);
						//不为空表示链表存在元素,将链表尾部的 next 置空,为了防止原先链表该元素的后面存在元素
						if (loTail != null) {
							loTail.next = null;
							newTab[j] = loHead;
						}
						if (hiTail != null) {
							hiTail.next = null;
							newTab[j + oldCap] = hiHead;
						}
					}
				}
			}
		}
		return newTab;
	}

HashMap get() 方法

get() 方法调用 getNode() 方法获取节点,并进行判空操作,进而返回 null 或值

public V get(Object key) {
	HashMap.Node<K,V> e;
	return (e = getNode(hash(key), key)) == null ? null : e.value;
}

getNode() 方法如下

final HashMap.Node<K,V> getNode(int hash, Object key) {
	//tab 引用当前 HashMap 的散列表
	//first 链表头节点或红黑树根节点
	//e 临时节点
	//n 散列表长度
	HashMap.Node<K,V>[] tab; HashMap.Node<K,V> first, e; int n; K k;
	//散列表不为空,且路径寻址后的位置存在元素
	if ((tab = table) != null && (n = tab.length) > 0 &&
			(first = tab[(n - 1) & hash]) != null) {
		//若 key 一致,直接返回
		if (first.hash == hash && // always check first node
				((k = first.key) == key || (key != null && key.equals(k))))
			return first;
		//若该位置的 next 不为空,说明已经链化或树化
		if ((e = first.next) != null) {
			//若树化
			if (first instanceof HashMap.TreeNode)
				return ((HashMap.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);
		}
	}
	return null;
}

HashMap remove() 方法

remove() 方法有两种,两个参数的 remove() 方法需要 value 也匹配成功,二者均调用 removeNode() 方法

public V remove(Object key) {
	HashMap.Node<K,V> e;
	return (e = removeNode(hash(key), key, null, false, true)) == null ?
			null : e.value;
}

@Override
public boolean remove(Object key, Object value) {
	return removeNode(hash(key), key, value, true, true) != null;
}

removeNode() 方法如下

final HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
								   boolean matchValue, boolean movable) {
	//tab 引用当前 HashMap 的散列表
	//p 表示当前的元素
	//n 表示 table 数组(散列表)的长度
	//index 表示路由寻址结果(散列表索引)
	HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, index;
	//散列表不为空,且路径寻址后的位置存在元素
	if ((tab = table) != null && (n = tab.length) > 0 &&
			(p = tab[index = (n - 1) & hash]) != null) {
		//临时节点、key 和 value
		HashMap.Node<K,V> node = null, e; K k; V v;
		//若 key 一致,说明找到目标元素
		if (p.hash == hash &&
				((k = p.key) == key || (key != null && key.equals(k))))
			//用 node 记录目标元素
			node = p;
		//若当前元素的 next 不为空,说明已经链化或树化
		else if ((e = p.next) != null) {
			//若树化
			if (p instanceof HashMap.TreeNode)
				node = ((HashMap.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 = e;
				} while ((e = e.next) != null);
			}
		}
		//目标元素存在,且用 node 指定,判断是否需要进行值匹配验证
		if (node != null && (!matchValue || (v = node.value) == value ||
				(value != null && value.equals(v)))) {
			//若树化
			if (node instanceof HashMap.TreeNode)
				((HashMap.TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
			//若为单个节点
			else if (node == p)
				tab[index] = node.next;
			//若链化
			else
				p.next = node.next;
			//增加修改次数
			++modCount;
			//减少 size
			--size;
			afterNodeRemoval(node);
			return node;
		}
	}
	return null;
}

HashMap replace() 方法

replace() 方法有两种,三个参数的 replace() 方法需要对传入的 oldValue 与实际的 oldValue 进行比对

实现逻辑上,调用 getNode() 方法找到目标元素,进行值的替换即可

@Override
public boolean replace(K key, V oldValue, V newValue) {
	HashMap.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;
}

@Override
public V replace(K key, V value) {
	HashMap.Node<K,V> e;
	if ((e = getNode(hash(key), key)) != null) {
		V oldValue = e.value;
		e.value = value;
		afterNodeAccess(e);
		return oldValue;
	}
	return null;
}

常见问题

1. 为什么 JDK1.8 中 HashMap 要引入红黑树?

当哈希冲突过多时,链表长度过长,影响存取效率,在极端情况下,甚至时间复杂度可以达到O(n),故引入红黑树以提高性能

2. 为什么 JDK1.8 中 HashMap 引入红黑树而非 AVL 树?

对于AVL 树,比红黑树保持更加严格的平衡。AVL树中从根到最深叶的路径最多为 ~1.44 lg(n + 2),而在红黑树中最多为 ~2 lg(n + 1),因此,在 AVL 树中查找通常更快,但这是以更多旋转操作导致更慢的插入和删除为代价的

也就是说,对于 AVL 树,有着更高的查找性能,但红黑树在牺牲一些查找性能后,获得了较高的插入删除效率,

对于通常情况,经过功能、性能、空间开销的折中,选择红黑树

3. 为什么不一直使用红黑树,而是要做链表和红黑树的转换?

默认情况下,链表长度达到 8 则自动转换成红黑树,而当长度降到 6 则转换回去

如果 hashCode 分布良好,也就是 hash 计算的结果离散性较好时,各个值都均匀分布,很少出现链表很长的情况,此时仍然能保持较高的查询效率,无需进行红黑树转换,只有当链表长度超过阈值,查询效率降低时,才需进行红黑树转换

4. 为什么要使用扰动函数 hash() ?

若不使用扰动函数,路由寻址计算时只取较低位的信息,高位信息被忽视,从而可能造成严重碰撞,通过扰动函数,将高位信息也蕴含在低位中,使得结果更加均匀

5. 为什么要使用与运算进行取模?

由路由寻址公式 (h = key.hashCode()) ^ (h >>> 16) & (length - 1) 可以看出,结果需要进行与运算

若直接使用 key.hashCode() 计算出哈希值,则范围为:-2147483648 到 2147483648,大约 40 亿的映射空间,范围过大,无法放入内存中,且 HashMap 的初始容量为 16 ,故必须要进行与运算取模

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值