一、概述
jdk8中hashmap的结构如图所示,它是由数组+链表+红黑树组成,jdk8之前是由数组+链表组成,那么为什么要这么做那?让我们带着疑问一步步往下看。首先看下这几个基本组成结构:
- 数组:数组存储结构是连续的,空间复杂度大,但查询的时间复杂度小。其寻址(通过下标搜索)效率高,一般的插入和删除效率低。
- 链表:链表存储结构是离散的,空间复杂度小。其寻址(通过下标搜索)效率低,一般的插入和删除效率高。
- 红黑树:作为一种二叉查找树,但它在二叉查找树的基础上增加了着色和相关的性质使得红黑树相对平衡,从而保证了红黑树的查找、插入、删除的时间复杂度最坏为O(log n)。由于链表的查询时间复杂度为O(n),所以当链表很长时转换成红黑树将很好的提高效率!
二、源码分析
1、成员变量
//初始容量,默认为16,必须为2的指数倍
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量,必须为2的指数倍
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因数
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树化阈值,当桶中链表的长度大于8时将其转换为红黑树
static final int TREEIFY_THRESHOLD = 8;
//链表化阈值,当resize或删除操作时,桶中的元素数低于该值,将把红黑树转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
//容器可以被树形化的最小容量,应该至少是4 * TREEIFY_THRESHOLD以避免调整大小和树状化阈值之间的冲突
static final int MIN_TREEIFY_CAPACITY = 64;
//存储元素的数组,第一次使用时初始化
transient Node<K,V>[] table;
//缓存entrySet
transient Set<Map.Entry<K,V>> entrySet;
//map的大小即map中包含的键值对的大小
transient int size;
//map被结构修改的次数,map被迭代时采用fail-fast机制
transient int modCount;
//扩容阈值,threshold = capacity * load factor
int threshold;
//当前负载因数,用来衡量hashmap空间占比情况,计算方法是size/capacity
final float loadFactor;
链表的结构代码 :
//为单向链表
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;
}
//两个节点只有键和值都相等时才返回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;
}
}
红黑树结构代码,红黑树的讲解可以参考该博客红黑树详解:
/**
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
*/
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);
}
2、构造方法
//默认构造方法,构造空元素的hashmap,初始容量为16,负载因数为0.75
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//用指定初始值构造一个空的hashmap,其负载因数为默认的0.75
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//用指定的容量和负载因数构造一个空的hashmap
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
//返回2的指数倍
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
//以指定的map集合构造成一个新的hashmap,其负载因数为默认0.75,容量根据原有的map来调整
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
以上有个tableSizeFor方法,为什么总能返回2的指数倍,细节参考该博客HashMap源码注解 之 静态工具方法hash()、tableSizeFor()(四)。之所以保证要返回2的指数倍,是为了提高hash的效率。
3、常用方法
3.1、size:返回map的容量即键值对数量。
public int size() {
return size;
}
3.2、isEmpty:map是否为空。
public boolean isEmpty() {
return size == 0;
}
3.3、 get(Object key):返回指定键对应的值。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//key的hash值高16位不变,低16位与高16位异或作为key的最终hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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) {
//首先检查首节点是否与指定key匹配
if (first.hash == hash &&
((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 {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
上面涉及到hash方法,它的实现方法是key的hash值高16位不变,通过低16位与高16位异或作为key的最终hash值,这样简单的异或可以在系统开销不大的情况下,适当的减少碰撞。细节参考该博客HashMap源码注解 之 静态工具方法hash()、tableSizeFor()(四)。
3.4、 containsKey(Object key):map中是否存在指定的键。
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
3.5、put(K key, V value):将指定的键和值关联,若原来存在相应的键值对,则将原来的值覆盖。
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;
if ((tab = table) == null || (n = tab.length) == 0)
//如果map为空,进行扩容操作
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))))
//若键值及hash值能匹配,覆盖链表的旧值
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;
}
以下的图能形象的描述put逻辑的整个流程:
3.5.1 扩容机制的原理
下面是扩容机制的代码,扩容的逻辑是第一次时容量设置为16,后面每次扩容为原来的2倍,直到最大容量。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//若原来的容量大于0
if (oldCap > 0) {
//若容量大于最大容量值,将扩容阈值设置为Integer的最大值,直接返回原来的节点数组
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
}
//若原来的容量为0但原来的扩容阈值大于0,将新的容量设置为原来的扩容阈值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//若原来的容量和扩容阈值都为0,将新的容量和扩容阈值都设置为默认的容量和扩容阈值
else { // zero initial threshold signifies using defaults
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;
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;
//遍历时分为两种节点,(e.hash & oldCap)==0为一种节点;否则为另外一种节点
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);
//若loTail 节点不为空,则放在新表原位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//若hiTail 节点不为空,则放在新表往后移动oldCap的位置
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
三、总结
- hashmap底层结构是由数组+链表+红黑树组成,当链表长度大于8且容量大于最小树化容量时将转换成红黑树,这些使得hashmap能兼顾增删改查的性能。
- hashmap默认的容量为16,默认负载因数为0.75,当其容量大于扩容阈值(容量 * 负载因数)时,将进行扩容操作,每次扩展为原来的2倍,且必须保证为2的指数倍。
- 当发生hash碰撞时,hashmap采用的是链地址法,及在存在相同hash值的数组位置存放链表。
- hashmap不是线程安全的,可以使用Collections.synchronizedMap()来封装不安全的HashMap的方法。
参考链接:
https://blog.csdn.net/zjxxyz123/article/details/81111627
https://blog.csdn.net/fan2012huan/article/details/51097331
https://blog.csdn.net/qpzkobe/article/details/78948197
https://www.cnblogs.com/CarpenterLee/p/9558026.html
https://blog.csdn.net/mbshqqb/article/details/79799009
https://www.cnblogs.com/yyxt/p/4983967.html