jdk1.8 hashmap源码解析
hashmap存储形式
网上找的图:
存储:数组+链表+红黑树
一、主要常量和属性
常量:
DEFAULT_INITIAL_CAPACITY = 1 << 4:存储节点的数组table的默认长度
MAXIMUM_CAPACITY = 1 << 30:存储节点的数组table的最大长度
DEFAULT_LOAD_FACTOR = 0.75f:默认负载因子
TREEIFY_THRESHOLD = 8:链表转换成红黑树的阈值
UNTREEIFY_THRESHOLD = 6:红黑树转换成链表的阈值
MIN_TREEIFY_CAPACITY = 64:转换成红黑树时最小的容量,若不足容量,只会发生数组的扩容
map中的节点:静态内部类Node
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;
}
...
}
属性:
transient Node<K,V>[] table; //存储节点的数组
transient int size; //map中的容量
transient int modCount; //hashmap在结构上被更改的次数
int threshold; //要扩容的阈值(容量*负载因子),此外,如果尚未其分配数组(及table),字段保存初始数组容量,或零用来表示默认初始容量
final float loadFactor; //负载因子
定位数组中的位置:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
int index=hash&(table.length-1); //在数组中的位置
二、常用方法
1.构造方法
- 传入初始容量和负载因子
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);
}
- 只传初始容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR); //负载因子使用默认的
}
- 什么都不传
public HashMap() {
//负载因子使用默认
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2.resize方法
初始化table或table扩容时,用resize()方法
final Node<K,V>[] resize() {
//oldTab记录旧数组
Node<K,V>[] oldTab = table;
//oldCap记录旧数组的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//旧数组的长度大于0,即旧数组被初始化过
if (oldCap > 0) {
//table的长度大于最大长度,将阈值设为Integer.MAX_VALUE,返回
//旧数组
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//新数组的长度为旧数组的2倍,阈值也为旧数组阈值的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
//旧数组的长度为0并且旧数组阈值大于0
else if (oldThr > 0)
//新数组的长度为旧数组的阈值
newCap = oldThr;
else { //旧数组的阈值为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,table设置为newTab
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) {
//e记录旧数组的节点
Node<K,V> e;
if ((e = oldTab[j]) != null) {
//将旧数组的节点设置为空
oldTab[j] = null;
if (e.next == null)
//旧数组的位置只有一个节点,计算该节点在新数组的索引,直接放入新数组
newTab[e.hash & (newCap - 1)] = e;
//如果是红黑树节点,进行红黑树的重hash分布
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//旧数组节点下还有链表,jdk1.8之后采用尾插法
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;
}
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;
//table还没被初始化或者table的长度为0
if ((tab = table) == null || (n = tab.length) == 0)
//调用resize()方法对table进行初始化,n记录初始化的长度
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;
//p指向的是旧表该索引处的值,p的hash值与传入的hash值一样并且p的键值和传入的键值一样,
//说明找到了相同的key值,将p赋值给e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断p节点是否为TreeNode, 如果是则调用红黑树的putTreeVal方法查找目标节点
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//p不是要找的key值
else {
//遍历链表
for (int binCount = 0; ; ++binCount) {
//p下没有节点了,将新节点放入p的下面
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//检查节点数是否超过8个,如果超过则将链表转换成红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
//e指向的是链表中的节点,如果e的hash值和传入的hash值相同并且key值也相同
//说明找到了相同的key值,跳出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//p指向它的下一个节点
p = e;
}
}
//如果e不等于空,说明之前在数组中找到过相同的key值
if (e != null) {
V oldValue = e.value; //旧值
if (!onlyIfAbsent || oldValue == null)
e.value = value;//新值覆盖旧值
afterNodeAccess(e);
return oldValue; //返回旧值
}
}
++modCount;
if (++size > threshold) //加入节点后容量超过阈值,用resize()扩容
resize();
afterNodeInsertion(evict);
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;
}
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;
//数组不等于空&&数组的大小大于0&&计算求得的索引处不为空
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;
//p指向的是计算求得的索引处的值
//如果p的hash值与传入的hash值相同&&key值与传入的key值相同
//说明找到了要删除的值,将p赋值给node
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//p下有值,将p.next赋值给e
else if ((e = p.next) != null) {
//如果p是TreeNode则调用红黑树的方法查找节点
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {//p是普通链表,用do-while循环遍历
do {
//找到目标节点,将目标节点赋值给node并跳出循环
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;//记录目标节点的前一个节点
} while ((e = e.next) != null);
}
}
//node记录的是目标节点
//node不为空说明找到了目标节点并且node的值与传入的值相同
if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
//如果是TreeNode则调用红黑树的移除方法
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//目标节点是头几点
else if (node == p)
tab[index] = node.next;
else //p记录的是目标节点的前一个节点
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node; //返回被移除的节点
}
}
return null;
}
get方法
传入key值返回key对应的value
public V get(Object key) {
Node<K,V> e;
return (e = getNode(key)) == null ? null : e.value;
}
final Node<K,V> getNode(Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
//表不为空&&表的长度大于0&&计算所得索引处不为null
//first指向头结点
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & (hash = hash(key))]) != null) {
//first的hash值等于传入的hash值&&first的key值等于传入的key值
//说明first为目标节点,返回first
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//first以下还有节点
if ((e = first.next) != null) {
//如果是红黑树节点,则调用红黑树的查找目标节点方法getTreeNode
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
//e是目标节点,返回e
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null; //没找到,返回null
}
版权声明:本文为dycyjb原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。