HashMap是Java Map子类中最常用的,接下来我将讲解HashMap的底层原理(建议先复习《数据结构》的散列表),会涉及到源码分析。
一、数据保存
HashMap是一个用于存储键值对的集合,每一个键值对也叫做Entry(在Map接口中定义)。这些个键值对(Entry)分散存储在一个数组当中,这个数组就是HashMap的主干,这个数组就是数据结构中的散列表,并且HashMap采用拉链法来解决冲突。HashMap数组每一个元素的初始值都是Null。
Java HashMap散列表定义,Node是Entry的子类
transient Node<K,V>[] table;
二、构造函数
我们看看HashMap的3个构造函数
1.最常见的就是无参的构造函数
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
只有一行代码,就是将负载因子初始化为默认的值
跳过去看,默认的负载因子是0.75,f表示float浮点型,Java默认把小数解析为double双精度浮点型。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
散列表还有个重要的属性就是容量大小,这会涉及到hash冲突、扩容等等。从下面这行代码我们可以看到初始容量是16。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
2.第二常用的就是指定容量的构造函数
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
调用了另外一个构造函数,我们接着看
3.指定容量和负载因子的构造函数
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);
}
简单介绍下代码逻辑:
1.initialCapacity<0则抛异常
2.大于MAXIMUM_CAPACITY则取MAXIMUM_CAPACITY,查看源码发现HashMap最大容量为2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
3.负载因子loadFactor检查
4.赋值负载因子和threshold
我们跳进去看看tableSizeFor,方法名很明显就是计算散列表大小
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;
}
这里看上去很复杂,目的是计算出一个大于等于cap的最小二次幂。
位运算就是把最高位的1的位置,赋值给其右边所有的位数。对5(二进制:101)进行如上操作,得到7(二进制:111),最后+1得到8(二进制:1000)。
1. 101 | 10(101 >>> 1) = 110
2. 110 | 001(110 >>> 2) = 111
3. 111 | 000(111 >>> 4) = 111
4. 111 | 000(111 >>> 8) = 111
5. 111 | 000(111 >>> 16) = 111
问:为什么要cap-1,最后+1
答:如cap正好二次幂,会计算出大于cap的最小二次幂,而不是恰好cap。举个例子:4经过如上操作会得到8,但是我们需要4。
但是为什么要计算出大于等于cap的最小二次幂,我们看下一节。
三、Hash函数
常用的hash函数就是取模,在HashMap也是这样,但是直接用%操作符取模性能堪忧。所以HashMap的设计者用位运算来优化,不过模数只能是二次幂。
普通的取模:i = key.hashCode() % Length
putVal方法源码(部分):
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
源码里面的n是表的长度(二次幂),我们先关注位运算:
如101110001110101110 1001对10000(十进制:16)取模,等效于101110001110101110 1001和1111(十进制:15)做与运算。
采用二次幂作为模数,Hash算法最终得到的index结果,完全取决于Key.Hashcode()的最后几位。
Java8源码采用了hash(key)来计算而不是直接使用key.hashCode(),是为了均匀。因为hash表的长度比较小,直接使用key.hashCode()只是用到了低位,而hash(key)先将高低位做了一次运算。
如果key为null,hash方法返回0,因为HashMap可以保存最多一个null值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
四、Put方法原理
简单说下putVal方法的原理
1. 表为空则resize()
2. 计算value的插入点i,如果空直接插入
3. 如果不为空则判断key是否存在,若存在则覆盖之前的值,没有的话采用头插法插入链表
4. Java8中如果节点数大于8,则会采用红黑树存储
说实话,这段源码的可读性有点差,反正我是没完全看明白
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)
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);
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;
}
五、Get方法原理
了解了put方法,get方法就很简单,就是计算hash值,然后去散列表取值。
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;
}