目录
HashMap源码分析
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
一、简介
HashMap的数据结构从jdk 1.8开始,从jdk1.7的数组+链表结构调整为数组+链表+红黑树。在HashMap中元素个数超过64时,链表长度大于等于8时,链表转化为红黑;当红黑树的大小小于等于6时,红黑树转为链表。在链表插入元素时,从jdk1.7的头插法改为尾插法,以防止死循环。HashMap的大小只能是2次幂,当不指定长度初始化时,初始化大小默认16。在元素大小达到默认负载因子0.75的阈值时,会动态扩容。之所以选择0.75作为扩容的阈值,是因为默认负载因子 (.75) 在时间和空间成本之间提供了良好的折衷。较高的值会减少空间开销,但会增加查找成本(反映在HashMap类的大多数操作中,包括get和put )。
二、主要类成员变量
常量
// 默认数组初始容量,必须为2的幂次方大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量,如果一个更高的值由任何一个带参数的构造函数隐式指定时使用。必须是 2 <= 1<<30 的幂
static final int MAXIMUM_CAPACITY = 1 << 30;
// 构造函数中未指定时使用的负载因子,扩容阈值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转化为红黑树的阈值
static final int TREEIFY_THRESHOLD = 8;
// 红黑树退化为链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 链表转为红黑树时需要满足的的最小表容量(数组大小)
static final int MIN_TREEIFY_CAPACITY = 64;
成员变量
// 节点初始化与扩容的数组
transient Node<K,V>[] table;
// 节点set集合(平时遍历Map用的就是这个)
transient Set<Map.Entry<K,V>> entrySet;
// map的元素个数
transient int size;
// 结构修改次数
transient int modCount;
// 要调整大小的下一个大小值(容量 * 负载因子)
int threshold;
// 哈希表的负载因子
final float loadFactor;
三、内部类
1、Node
链表结构
// hashmap中的节点结构
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;
}
}
2、TreeNode
二叉树结构上的节点
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);
}
}
看下LinkedHashMap.Entry<K,V>,可以看出TreeNode<K,V>依赖HashMap.Node<K,V>
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
四、构造方法
1、HashMap()
public HashMap() {
// 默认扩容负载因子0.75
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
2、HashMap(int , float)
根据传值的初始数组容量和负载因子构参
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
// 当初始容量超过1<<30时,及2的三十次方大小,默认数组长度为MAXIMUM_CAPACITY
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);
}
谈谈关于tableSizeFor算法的理解
// 返回大于等于cap的最小的2的幂
static final int tableSizeFor(int cap) {
int n = cap - 1; // 这一步为了防止已经是2次幂的值,后面再次扩大两倍
// 这几次的操作比较灵性。
// 首先我们要知道,2次幂是一定只存在一位bit位为1且为最高位,其余均为0。
// 比如一个十进制64,int是32位,首位为符号位,正数默认第一位为0。
// 所以32位二进制后转为:0000 ....(5次0000) 0100 0000
// >>> 为无符号右移,|为或运算(存1为1)。
// int无论是什么数(n),肯定存在最高位为1。当后面所有bit位转换为0时,转换后的数(m)一定是2的幂次方,而且m一定是小于等于n的(最大2的幂次方);当后面所有bit位转换为1时,转换后的数(m)一定是大于等于n的(最小2的幂次方-1)
// 所以,我们可以理解,由于int32位,以十进制64举例:
// 在经过以下5步转换后,一定可以得到 0000 ....(5次0000) 0111 1111。其实在代码到n |= n >>> 4;时,就已经是了,后面其实是为int类型最高位较大时准备的。
// 所以 0000 ....(5次0000) 0111 1111 在 +1 操作后,就一定是大于或等于传入cap的最小2的幂。
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;
}
3、HashMap(int)
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
4、HashMap(Map<? extends K, ? extends V> m)
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
// evict – 最初构造此映射时为 false,否则为 true(中继到方法 afterNodeInsertion)
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
// 当Node<K,V>[]数组为空时,计算出数组初始大小(按照0.75的阈值去计算)
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);
}
}
}
五、主要方法
* hash
取key的hash值,通过这个方法计算出所在table[]数组的下标。
由此也可以看出,HashMap是允许key为null的,会将key为null的Node,放在索引为0的位置。(h = key.hashCode()) ^ (h >>> 16) 的解释就是取key的hashcode与此hashcode无符号右移16位做异或运算(异或:相同为0,相异为1),也叫扰动函数。
为什么这么做?
当我们打算放置一个元素时,我们首先要计算这个元素在数组的index。由于对象的hash()方法,返回的是一个int类型(32位)。所以我们可以用这个hash值去对这个数组长度取余操作(hash%table.length)去得到索引位置,这也是我们取下标位置最简单的一种操作。
当数组大小为2的幂时,我们的%操作可以转换为&操作,hash%table.length 等价于 hash&(table.length-1)。
例如:
当数组(table.length)大小为16,hash值假设为20。
20 % 16 = 4 取余得出index=4。 当转换为2进制做与&运算时,如下(取八位二进制,实际int是32位二进制)
20: 0001 0100
& ====> 0000 0100 ====> 4 得出index=4,所以可以得出上述结论。
15: 0000 1111
其实由上面的例子也能看出,在&运算时,只有最后四位参与了运算,因为0与上任何都为0,相当于没有改变,最后得到的数是一定不超出数组大小的。但是,我们发现。这样操作时,hash只有最后四位有效,高位&上0,无论是0还是1,实际上都是无效运算。又因为int为32位,所以取个中位数,把高16位右移至低16位,在通过异或(^)运算,就可以把高位的特征也保留下来。
ps:解释下为啥要用异或(^)?这个是由于异或更加具有扰动性,如果使用或运算(|)或者与(&)运算,都会偏向1或者0。对低16位融入高16位的特征不如异或变动大。
总结:
hash(Object key)操作个人理解就是把低16位融入高16位的特征,在后面做hash&(table.length-1)取索引下标时更加随机,使插入元素的分布更加均匀。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
1、put
public V put(K key, V value) {
// 通过hash(key)对key的
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)
// resize() 初始化数组或者对数组扩容
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);
// binCount >= 7 ,相当于链表长度达到8,树化
// 在treeifyBin方法中,如果数组大小不超过64时,先做数组扩容操作
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;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 当数组大小不超过64时,先做数组扩容操作,不进行树化
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
2、get
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
inal 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 &&
// (n - 1) & hash 计算出当前key在数组中的索引位置
(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) {
// 如果数组下面挂的是数节点,调用getTreeNode方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 这里相当于数组挂的是链表,沿着next指针一直查下去。存在则返回,不存在在达到链表末端时结束循环
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
3、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;
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);
}
}
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;
}
4、clear
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
5、putAll
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}