HashMap源码笔记-基于jdk1.8
HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
HashMap 的实现不是同步的,这意味着它不是线程安全的。它的key、value都可以为null。此外,HashMap中的映射不是有序的,当然也是不可重复。
几个重要的属性
//默认初始容量为16,0000 0001 右移4位 0001 0000为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量为int的最大值除2
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认加载因子为0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//阈值,如果主干数组上的链表的长度大于8时,链表转化为红黑树
static final int TREEIFY_THRESHOLD = 8;
//hash表扩容后,如果发现某一个红黑树的长度小于6,则会重新退化为链表
static final int UNTREEIFY_THRESHOLD = 6;
//当hashmap容量大于64时,链表才能转成红黑树
static final int MIN_TREEIFY_CAPACITY = 64;
//临界值=主干数组容量*负载因子
int threshold;
HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量 是哈希表中桶的数量,初始容量 只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有两倍的桶数。
数据结构
HashMap 是一个散列表,内部是一个数组形式的链表 table,它存储的内容是键值对(key-value)映射。
//数组形式,以静态内部类实现的链表
transient Node<K,V>[] table;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
默认大小是16,最大是1073741824(2的30次方);如果设置了大小,会寻找比设置值大一点的2的幂或它本身(本身是2的幂),如果设置值比1073741824,则为1073741824。
/**
* 构造函数
* @param initialCapacity 初始化大小
* @param loadFactor 装载因子
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//MAXIMUM_CAPACITY 即最大值
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//Float.isNaN() 判断 float 是否是合法数字,如0.0f/0.0f就不是
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
/**
* 构造方法中,并没有对table这个成员变量进行初始化,table的初始被推迟到了put方法中,
* 在put方法中会对threshold重新计算
* this.threshold = tableSizeFor(initialCapacity) * this.loadFactor;
*/
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 寻找大于等于cap的最小的2的幂
* /
static final int tableSizeFor(int cap) {
/**
* 为了防止,cap已经是2的幂。如果cap已经是2的幂, 又没有执行
* 这个减1操作,则执行完后面的几条无符号右移操作之后,返回的值
* 将是这个cap的2倍
*/
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;
}
读者注意HashMap的构造函数没有限制initialCapacity不能传0,根据tableSizeFor函数,传0的时候返回-1,也就是threshold 值为-1,当我们往HashMap塞值的时候会报错吗?让我们继续往下看
基本操作
put(K key, V value)
往HashMap添加元素时,会先判断 table 是否为null,长度是否为0,如果是的话则调用函数resize() 初始化table,在resize()函数中使用我们传入的初始化大小和装载因子, 此时初始大小为0时,使用默认大小16,所以上面讲到的我们在构造函数中传0就会变成使用默认大小了。另外resize()函数还负责一个重要功能–扩容。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//原来table容量大于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
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//使用默认的table大小和阈值
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
@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;
/* 判断扩容是否要变位置,即判断二进制最高位,为0则不变,扩容前的元素地址为 (oldCap - 1) & e.hash ,
* 扩展后e.hash & (newCap - 1),newCap是oldCap的2倍,
* 例1:hash是00100,oldCap是10000,原始位置是4,扩展位置还是4;
* 例2:hash是11000,oldCap是10000,原始位置是8,扩展位置还是24;
* 所以这里的新的地址只有两种可能,一是地址不变,二是变为 老位置+oldCap,因此也就不用考虑扩容重建table时发生碰撞
*/
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;
}
table初始完后,若要添加到HashMap中的键值对对应的key已经存在HashMap中,则找到该键值对;然后新的value取代旧的value。
若要添加到HashMap中的键值对对应的key不在HashMap中,则将其添加到该哈希值对应的链表中。
/**
* onlyIfAbsent 如果为true,则不允许改变已存在的值
* evict 用于LinkedHashMap中的尾部操作,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;
//table为空,初始化
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))))
//hash相同并且key相同,则替换,见下面代码
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;
}
//hash相同并且key相同,则替换,见下面代码
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;
//此方法是为继承HashMap的LinkedHashMap类服务的,HashMap只是空实现
afterNodeAccess(e);
return oldValue;
}
}
//记录HashMap的修改次数,在forEach等迭代时会校验该值,不同时抛出ConcurrentModificationException()
++modCount;
//大小超过阈值,则扩容
if (++size > threshold)
resize();
//此方法是为继承HashMap的LinkedHashMap类服务的,HashMap只是空实现
afterNodeInsertion(evict);
return null;
}
另外HashMap允许put(null,null),此时会放在table数组的0位置,因为null的hash总是0
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这里hash的方法有点意思,这段代码叫扰动函数,将hashCode(32位)右移16位再取异或(对应位值相同,则结果为0,否则为1),把高位和低位的特征混合在一起,这样减少得到的散列值发生碰撞的可能。
get(Object key)
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 {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
remove(Object key)
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
//存在该hash对应节点,则寻找对象
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);
}
}
//找到对象,执行移除
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
//红黑树
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
//普通节点
tab[index] = node.next;
else
//链表
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
码字不易,希望有助于他人~