HashMap实现原理
前言
HashMap原理相信很多小伙伴在面试的时候都有被问到,hashmap是一种很重要的数据结构之一,并且在我们开发过程中用的也是比较多的。网上也有很多关于hashmap的介绍,在这里我也写写我的一点理解~~
源码分析
在jdk1.7和1.8版本中hashMap的实现方式是有所不同的,在jdk1.7及之前,是用数组+链表的方式实现,在jdk1.8中,当链表达到某个条件后就会转为红黑树,也就是说在jdk1.8中,hashmap是用 数组 + 链表 + 红黑树的方式实现。
如下图所示:
话不多说,上源码:
先看一下HashMap中各个常量的含义:
/**
* 默认容量大小,左移运算(计算机中位运算效率高),默认值 16
* The default initial capacity - MUST be a power of two.
*/
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;
/**
* 链化的最小值,当HashMap树化后,实际元素个数减少时,单个红黑树的元素个数小于该值时,会转回链表
* 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;
/**
* 最小的树化容量,即当hashmap树化时,还需要当前hashmap中的总元素个数大于该值
* 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.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
默认无参构造器:
public HashMap() {
// 使用默认的扩容因子,即 0.75
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
接下来看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.
*
* @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>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 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是node数组,也就是本文上述图中的Node<K,V>[] table
if ((tab = table) == null || (n = tab.length) == 0)
// 当hashmap为空或长度为0,则进行初始化(resize方法后续会讲到,该方法当map为空时进行初始化,不为空进行扩容)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 当key不存在table中时,直接新增一个Node放到当前位置
tab[i] = newNode(hash, key, value, null);
else { // 当key的hash值在某个位置存在时(hash值可能相同,也可能不同,但是映射到table数组的同一个位置上)
// 当key的hash相同,且equals返回true,说明时同一个key,这时候先用 Node<K,V> e 指向改Node,稍后会根据boolean onlyIfAbsent值判断是否覆盖值
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
// 若节点时TreeNode类型,也就是已经树化了,这时候只需要把当前key添加到树中
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 没有树化的情况,这里binCount作用是记录当前链表的长度
for (int binCount = 0; ; ++binCount) {
// 当p的下一个节点是空,则添加到p的后面
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 这里就是用binCount来判断当前链表是否达到树化的要求,treeifyBin方法是进行树化
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;
// 这里就是当key相同是,判断是否覆盖值,在put方法中默认传的false,因此我们在使用hashmap时,key相同时,默认时覆盖操作
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
// 判断是否达到扩容值,threshold在下面resize方法中会提到
resize();
afterNodeInsertion(evict);
return null;
}
resize方法:
/**
* 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.
*
* @return the 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
// 首次初始化赋值,默认容量16,默认扩容阈值 0.75 * 16 = 12
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);
}
// 在put方法中,使用threshold判断是否扩容,threshold值在此处赋值
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) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
// e.hash & (newCap - 1) 计算元素在新数组中的位置,与put方法中一致
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// e.hash & oldCap 这个地方比较巧妙,假如扩容前大小时16,key计算出来的hash值为16时,数组下标是0,而扩容后下标为16,即把原来的链表根据key的hash值进行拆分
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
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方法和resize方法,以及hashmap中常量的意义,下期介绍hashmap的一些其他方法。如内容有误,欢迎各路大神指正。