一、前言
1.本文基于JDK1.8源码分析,会贴出涉及的相关数据结构及源码。
2.文中只涉及hashmap的put/get方法,代码理解附在注释上(直接看代码更清晰)。
3.JDK1.8中,HashMap采用位桶+链表+红黑树实现,当链表长度超过阈值(8)时,将链表转换为红黑树。
二、数据结构
1.单向链表
//单向链表,实现了Map.Entry接口 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; } //判断两个node是否相等,key与value均相等则返回true 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; } }
2.红黑树
//红黑树(太多了,放一些属性及构造函数) static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } }
3.位桶
transient Node<K,V>[] table;
三、主要属性
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量 static final float DEFAULT_LOAD_FACTOR = 0.75f;//填充比 //当add一个元素到某个位桶,其链表长度达到8时将链表转换为红黑树 static final int TREEIFY_THRESHOLD = 8; static final int UNTREEIFY_THRESHOLD = 6; static final int MIN_TREEIFY_CAPACITY = 64; transient Node[] table;//存储元素的数组 transient Set> entrySet; transient int size;//存放元素的个数 transient int modCount;//被修改的次数fast-fail机制 int threshold;//临界值 当实际大小(容量*填充比)超过临界值时,会进行扩容 final float loadFactor;//填充比(......后面略)
关于fast-fail可以看这篇https://blog.csdn.net/zymx14/article/details/78394464
四、put/get
1.get方法
static final int hash(Object key) { int h; //增加随机度 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
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; //hash & length-1 定位数组下标 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //检查首节点,hash与key均相等则返回 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { //首节点是树节点,则hashmap是采用位桶+红黑树结构,调用TreeNode.getTreeNode(hash,key),遍历红黑树 if (first instanceof TreeNode) return ((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; }
2.put方法
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //如果tab为空或长度为0则重新分配容器大小 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; (n-1) & hash找到put位置,槽为空则直接put成为首节点 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //第一个节点的hash值与要加入的hash值相等,key也相等 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) { //e为空,表示到表尾也没找到相同节点,则新建节点 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; } } //更新hash与key均相同节点的value值 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源码学习过程,只针对put/get方向性理解,有错误请指正,一起学习一起进步。
扫描二维码关注公众号,回复:
10377193 查看本文章
final Node[] resize() {
Node[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {//超过1>>30大小,无法扩容只能改变 阈值
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)//新的容量为旧的2倍 最小也是16
newThr = oldThr << 1; // 扩容阈值加倍
}
else if (oldThr > 0)
newCap = oldThr;//oldCap=0 ,oldThr>0此时newThr=0
else { //oldCap=0,oldThr=0 相当于使用默认填充比和初始容量 初始化
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[] newTab = (Node[])new Node[newCap];
//数组辅助到新的数组中,分红黑树和链表讨论
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node 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)e).split(this, newTab, j, oldCap);
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node 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;
}