HashMap的put方法原理

本篇内容基于JDK 1.8

一、HashMap的put方法流程如下图

HashMap的put方法原理_第1张图片

二、具体的源码分析

/**
 * 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.
 *
 * @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 key, or
 *         null if there was no mapping for key.
 *         (A null return can also indicate that the map
 *         previously associated null with key.)
 */
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;
    //通过hashCode()的高16位异或低16位实现
	return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
 * 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[] tab; Node p; int n, i;
	//底层存储数据的数组tab为空,进行第一次扩容,同时初始化tab
	if ((tab = table) == null || (n = tab.length) == 0)
		n = (tab = resize()).length;
	//计算要存储数据的下标index,如果当前位置为null,直接插入
	if ((p = tab[i = (n - 1) & hash]) == null)
		tab[i] = newNode(hash, key, value, null);
	else {
		Node e; K k;
		//tab[i]的首个元素就是key,直接覆盖
		if (p.hash == hash &&
			((k = p.key) == key || (key != null && key.equals(k))))
			e = p;
		//tab[i]为TreeNode,进行红黑树的插入
		else if (p instanceof TreeNode)
			e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
		//链表遍历
		else {
			for (int binCount = 0; ; ++binCount) {
				if ((e = p.next) == null) {
					p.next = newNode(hash, key, value, null);
					//链表长度大于8,转换为红黑树进行处理
					if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
						treeifyBin(tab, hash);
					break;
				}
				//找到已经存在的key,直接覆盖
				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;
	//数据插入完成,size超过了扩容的阀值(容量*负载因子),进行扩容
	if (++size > threshold)
		resize();
	afterNodeInsertion(evict);
	return null;
}

总结:

1.底层存储数据的数组,在第一次put元素的时候初始化,同时发生第一次扩容;

2.相比较JDK 1.8之前的版本,JDK 1.8在链表长度大于8的时候,会转化为红黑树处理,主要是基于效率的考量;

你可能感兴趣的:(Java基础)