Map是广义java集合框架中的另外一部分,HashMap作为基于哈希表的map接口的非同步实现,在我们的日常开发中使用频率很高,也是面试中必问的知识点,结合最近在读hashmap的源码,谈谈自己的理解。
1. HashMap概述:
HashMap:允许null key和 null value, 非线程安全,存在fail-fast错误,比如说iteration在使用过程中remove操作。内部是基于bulket的数组结构+链表结构+红黑树(jdk8),当bulket达到最大时,会扩展成tree结构(来自源码类注释)。通俗一点讲,就是一个“链表数组”,每个数组里面的元素存放的是链表表头的节点,如下图所示:
节点的声明:
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
...........
2. HashMap的构造函数
HashMap提供了三个构造函数:
HashMap():构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity):构造一个带指定初始容量和默认加载因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity, float loadFactor):构造一个带指定初始容量和加载因子的空 HashMap。
备注:其中初始容量(initialCapacity),负载因子(loadFactor)是影响性能的重要参数,初始容量代表数组的初始长度,负载因子代表数组填满的程度。
若负载因子越大,说明数组填满越多,但是冲突的机会越大,链表的长度会越长,查询就越慢;若负载因子越小,数组数据越稀疏,发生冲突的机会就越小,但是浪费空间越多,
负载因子尽量使用默认,因为这是经过测试,性能最好的数值。
3. HashMap的存取
(1)存储
HashMap的put方法执行过程可以通过下图来理解
核心源码如下:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
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)
e = ((TreeNode<K,V>)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);
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;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
(1)通过源码if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;我们知道,HashMap也是按照lazy-load原则,在首次使用的时候做初始化。
(2)p = tab[i = (n - 1) & hash]) == null这个主要是获取元素在数组中的位置,其中hash的获取源码如下:
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
利用hashCode高16位异或低16,有些数据计算的哈希值差异主要在高位,而hashmap里的hash寻址是忽略容量以上的高位的,避免类似情况下的hash碰撞,???
i: 如果tab为null,或者tab的长度为0,则resize()重新创建tab
ii : 若不为null
hash值相同,key相同:替换,根据onlyIfAbsent 是否替换值
不相同:放到树结构里面,或者插入链表中
(3)怎么放入链表中,如下源码
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;
}
通过链表的节点遍历,中间若是存在key一模一样的就停止,否者遍历模块到末尾(null)插入数据
treeifyBin(tab, hash);,当数组大于TREEIFY_THRESHOLD 则形成一棵树,接下来具体看下,treeifyBin的源码:
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
在解释这段源码之前,我解释下几个概念:
TREEIFY_THRESHOLD: 链表(桶)形成树的最小阈值(默认是8)
UNTREEIFY_THRESHOLD:一个树的链表还原阈值,当扩容时,桶中元素小于这个值,就会把树形的桶元素还原回链表结构
MIN_TREEIFY_CAPACITY:哈希表的最小树形化容量:当哈希表中的容量大于这个值时,表中的桶才能进行树形化,否则桶内元素太多时会扩容,而不是树形化,为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
当哈希表容量小于
MIN_TREEIFY_CAPACITY:直接扩容,
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
e 是哈希表中指定位置桶里的链表节点,从第一个开始
TreeNode<K,V> hd =
null
, tl =
null
;
//红黑树的头、尾节点
//新建一个树形节点,内容和当前链表节点 e 一致
TreeNode<K,V> p = replacementTreeNode(e,
null
);
红黑树下一章节会重点讲解......
接下里继续看下扩容:
4. resize()扩容
Initializes or doubles table size.
Java里的数组是无法自动扩容的,方法是使用一个新的数组代替已有的容量小的数组,就像我们用一个小桶装水,如果想装更多的水,就得换大水桶。这里先查看的是jdk1.7的源码:
void resize(int newCapacity) { //传入新的容量
Entry[] oldTable = table; //引用扩容前的Entry数组
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) { //扩容前的数组大小如果已经达到最大(2^30)了
threshold = Integer.MAX_VALUE; //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
return;
}
Entry[] newTable = new Entry[newCapacity]; //初始化一个新的Entry数组
transfer(newTable); //!!将数据转移到新的Entry数组里
table = newTable; //HashMap的table属性引用新的Entry数组
threshold = (int) (newCapacity * loadFactor);//修改阈值
jdK有关于引入红黑树,详见HashMap源码一览(中)......