什么是哈希表:
哈希表是一种数据结构,key-value型,可以通过其key高效地找到value
jdk1.8中是数组+链表/红黑树 结构实现的,把key通过hash算法映射到桶位数组下标中,如果发生冲突则以拉链法追加到该桶位的链表中,在查找时就可以根据key值进行hash运算,获取桶位下标从而高效获取对应的value值
实现源码
插入元素:put
public V put(K key, V value) {
//调用putVal函数(哈希key值,key,value,)
return putVal(hash(key), key, value, false, true);
}
transient Node<K,V>[] table;
//Implements Map.put and related methods.
//Params:
//@Params: hash – hash for key
//@Params: key – the key
//@Params: value – the value to put
//@Params: onlyIfAbsent – if true, don't change existing value
// 如果当前位置已存在一个值,是否替换,false是替换,true是不替换
//@Params: evict – if false, the table is in creation mode.
//Returns:
//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;
if ((tab = table) == null || (n = tab.length) == 0)
// resize()函数 -> Initializes or doubles table size.
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;
}
逐行看: 首先声明了两个变量:
//一个Node数组 tab
Node<K,V>[] tab;
//一个Node p
Node<K,V> p;
Node是HashMap的静态内部类
Basic hash bin node, used for most entries.
就是一个链表
//Node 实现了 Map.Entry接口 (The Map.entrySet method returns a collection-view of the map, whose elements are of this class. )
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;
}
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;
}
}
看到初始化时会调用resize()函数
static final int MAXIMUM_CAPACITY = 1 << 30;
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
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 (
//左移一位后 与 MAXIMUM_CAPACITY(最大容量) 比较
(newCap = oldCap << 1) < MAXIMUM_CAPACITY
&&
// oldCap 是否大于等于 DEFAULT_INITIAL_CAPACITY 默认初始值
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold 扩大为原来的2倍
}
// 初始容量被设定了
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 0.75 * 16 = 12
}
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"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// resize时 进行扩容的操作:对旧hashmap的元素进行迁移
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)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
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;
}
看着有点渗人
先看看整体的putVal()方法,其中调用resize()有两处:
//第一处:当数组为null或长度为0时,进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
...
//第二处:判断当++size超过阈值时,扩容
if (++size > threshold)
resize();
初始化会走:
static final int MAXIMUM_CAPACITY = 1 << 30;
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; //初始化时,oldCap = 0
int oldThr = threshold;
int newCap, newThr = 0;
//原数组非空
if (oldCap > 0) {
...
}
// 初始容量被设定了
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else {
//初始化时走这里
// zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 0.75 * 16 = 12
}
if (newThr == 0) {
...
}
threshold = newThr; // 12
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab; // 16
// resize时 进行扩容的操作:对旧hashmap的元素进行迁移
if (oldTab != null) { //这里不会进入
...
}
return newTab; // 返回一个初始化后的Node<K,V>[]
}
往HashMap中放入一个元素
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))))
//哈希值相等、同时equal相等,则把 e = p;
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);
// 如果链表长度大于8,转换成红黑树;这里注意数组如果容量小于MIN_TREEIFY_CAPACITY=64,则先resize()扩容 -> 来自 treeifyBin(tab,hash);
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;
}
再看发生扩容的情况
想到了个版本进入插入超过阈值时扩容的函数resize()
++modCount;
if (++size > threshold)
resize(); // 在这里打一个断点
afterNodeInsertion(evict);
return null;
put操作的流程:
-
获取key的hash值:
hash(key); -
对象的hashcode经过扰动函数
hash(),使得此hash值更散列 -
构造出Node
-
路由算法:找出node应该存放的桶位
(hash & (length-1))
逐步分析:
hash函数: hash()
/**
* 作用:让key的hash值的高16位也参与运算
* h右移 16位(4*4)
* 异或
* h
* (结果使得低16位具有高16位的特征)
**/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
寻址:
- 最简单的情况:寻址找到的桶位是null => 构建Node放入桶位下标位置
//第一次扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 寻址找到的桶位为null
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
这个算法是 (数组长度-1) 按位与 hash
因为数组长度为2的整数次幂,再减去1后得到的二进制除符号位外全为1,此时进行按位与可取得余数
而且效率更高
桶位已经有数据:即出现哈希冲突
进入else块
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
// 链表长度大于8 进入treeifyBin()方法
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 找到后跳出for循环
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;
}
}
扩容resize()
hashmap已经完成初始化后,一次正常的扩容流程:
// oldTab 指向 当前table
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
// 声明新容量、新阈值
int newCap, newThr = 0;
// 正常扩容时, oldCap>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
// 进入该判断的情况
// 1、new HashMap(initCapacity,loadFactor);
// 2、new HashMap(initCapacity);
// 3、new HashMap(map); //map有数据
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// new HashMap();
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);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 扩容前 table不为空
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)
// 计算桶位存放的数组下标【选址算法:取余】
newTab[e.hash & (newCap - 1)] = e;
// 是黑树
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 桶位已经形成链表
// 低位链表:存放在扩容之后的数组的下标位置,与当前数组的下标位置一致
Node<K,V> loHead = null, loTail = null;
// 高位链表:存放在扩容之后的数组的下标位置为 当前数组下标 + 扩容之前数组的长度
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 按位与 oldCap
// hash -> .... 1 1111 & 1 0000
// hash -> .... 0 1111 & 1 0000 => 0
if ((e.hash & oldCap) == 0) {
// 高位为0,存放到低位链中
if (loTail == null)
// 初始情况下,若loTail为null
// 则赋予 loHead低位链头节点
loHead = e;
else
// 低位链末尾节点不为null
// 让末尾节点下一个指针
loTail.next = e;
// 移动末尾节点到下一个指针
loTail = e;
}
else {
// 高位非0,存放到高位链中
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;
太秒了!
jdk1.8对链表的resize()扩容时的处理:
遍历桶位(若是链表)
把链表分成:高位链、低位链
这里的划分算法是:hash & oldCap 【哈希值按位与旧容量】
得到的结果: 旧容量为2的整数次幂,因此 即 按位与 ... 1 0000;
- 最后低位若为0,则划分为低位链;【数组下标不变】
- 若为1,则划分为高位链;【数组下标 = 原数组下标+oldCap】
提高了效率
get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n;
K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//不止一个元素,则需要判断是红黑树还是链表
if ((e = first.next) != null) {
//红黑树
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//链表
do {
// hash值比较、equals比较
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
remove方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* 同时匹配key和value才删除
**/
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab;
Node<K,V> p;
int n, index; // n长度;index数组桶位
if ((tab = table) != null && (n = tab.length) > 0
&&
(p = tab[index = (n - 1) & hash]) != null)
{
Node<K,V> node = null, e;
K k;
V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 红黑树
if (p instanceof TreeNode)
node = ((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)))) {
// 1、node是红黑树【树结点移除】
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
// 2、桶位元素既为查找结果,则将该元素的下一个元素放置入桶位中
else if (node == p)
tab[index] = node.next;
else
// 3、是链表
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}