HashMap源码解析(待续)
简介
hashmap是由数组+链表+红黑树组成的数据结构,有如下特点:
- 以key-value的形式存储数据,并且key和value都可以为null。
- 线程不安全,需要线程安全可使用CurrentHashMap。
- 无序,有顺序要求可以使用LinkedHashMap。
1、重要的成员变量
// 默认初始容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 扩容因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表树化最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
// 链表树化最小长度
static final int TREEIFY_THRESHOLD = 8;
// 数链表化最小长度
static final int UNTREEIFY_THRESHOLD = 6;
// 扩容因子,用了final修饰,初始化后不可变。
final float loadFactor;
// 数组,长度即容量
transient Node<K,V>[] table;
// 大小,不是容量
transient int size;
// 容量临界值,容量 * 扩容因子;未初始化时,如果大于0,代表初始化容量
int threshold;
值得一提的是,如果数组的容量没有达到MIN_TREEIFY_CAPACITY ,即使链表长度大于8,也不会执行树化。
2、构造方法
public HashMap() {
// 无参构造,设置扩容因子为默认值 0.75
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
public HashMap(int initialCapacity) {
// 设置初始容量,使用默认扩容因子 0.75
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
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);
}
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;
}
3、核心方法
3.1 内部类 Node
这个node对象为HashMap的结点,它有四个属性:hash、key、value、next。
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) {...}
public final boolean equals(Object o) {...}
}
3.2 添加数据 put()
HashMap插入元素的方法比较复杂,其中涉及到 扩容/初始化、树化、LRC算法以及大量的if-else判断。
先看put()方法的流程图:
该图仅作流程参考不一定准确,比如最后的扩容判断,如果key存在,则不需要++size和判断扩容。
这里只在代码中做一些逻辑上的简单注释。
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) {
// 头节点为null,直接插入
tab[i] = newNode(hash, key, value, null);
} else {
// 这个else的总体逻辑是找到key对应该插入的位置,即e指向目标节点
Node<K,V> e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)) )) {
// 如果头节点的key和插入key相同,e指向头节点
e = p;
} else if (p instanceof TreeNode) {
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
} else {
// 这里是个死循环
for (int binCount = 0; ; ++binCount) {
// next为null,新建节点插入末尾并判断是否需要树化
// 注意这里e已经指向p的下一个节点。 e = p.next
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
// 继续往下走说明next不为null,判断key是否相同,相同则跳出循环
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
break;
}
p = e;
}
}
// e != null 代表上面找到了e指向的节点,那么什么时候满足 e != null 呢?
// 我们插入节点会有两种情况:1、key不存在,插入新节点;2、key存在,替换旧值
// e != null就是key存在的情况,所以这里只是替换旧value
if (e != null) {
V oldValue = e.value;
// onlyIfAbsent:key相同时,value是否替换。
// 默认put方法 onlyIfAbsent 为false
if (!onlyIfAbsent || oldValue == null) {
// 存入value
e.value = value;
}
// 更新最新访问链表
// 具体实现在LinkedHashMap中
afterNodeAccess(e);
return oldValue;
}
}
// 走到了这里则代表key不存在,需要插入新的值,即新节点。
// 这种情况才需要执行size++以及判断是否需要扩容。
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
我们着重分析下面几个方法:
3.2.1 扩容 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;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
} else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
// 如果新容量(旧容量的两倍)小于最大容量并且旧容量大于16
// 注意 newCap = oldCap << 1,此时扩容已经完成
// 为什么旧容量要大于16呢?
newThr = oldThr << 1;
} else if (oldThr > 0) {
// 原始容量为0时,threshold代表扩容时的新容量。
newCap = oldThr;
} else {
// 默认初始容量和扩容阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
// 为什么这里新阈值会等于0?
// 在前面用threshold代表扩容容量时,并没有对阈值进行处理
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;
// 如果原数组不为空,则需要进行数据迁移。大致逻辑就是将原数据的hash与新容量得到位置插入
// 这里好像和LRU有关,等我搞懂了LinkedHashmap原理再补充。
if (oldTab != null) {...}
return newTab;
}
总结:
- 原始容量大于0,容量为MAXIMUM_CAPACITY,则扩容阈值设为Integer最大值,否则扩量翻倍。
- 原始容量等于0,threshold大于0,则扩容至threshold的大小。
- 如果上述条件都不满足,默认初始化扩容。
- 最后对扩容阈值进行处理。(threshold作为容量时并没有处理扩容阈值)
3.2.2 插入树节点 putTreeVal(HashMap<K,V> map, Node<K,V>[] tab, int h, K k, V v)
3.2.3 树化 treeifyBin(Node<K,V>[] tab, int hash)
下面的三个方法在HashMap中并没有相应实现,它的实现是在LinkedHashmap中,这里简单说明下:
3.2.4 afterNodeAccess(Node<K,V> p) { }
3.2.5 void afterNodeInsertion(boolean evict) { }
3.2.6 void afterNodeRemoval(Node<K,V> p) { }
3.3 获取数据 get()
获取数据的总体逻辑就是:
- 找到key对应的数组位置
- 节点为null则直接返回bull
- 不为null,先判断首节点是否为所需节点,是则直接返回
- 判断下一个节点是否为null,为null则返回
- 是树节点则按树的寻找逻辑
- 不是树则遍历到最后一个节点,找到则直接返回该节点
- 上面都没找到,默认返回null
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) {
// 数组长度大于0并且first != null ,即应查询的数组位置已经有节点了
// 接下来就要从第一个节点开始往下找到我们需要的节点
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;
}
3.4 其他方法
keySet()用于获取所有的key,values()用于获取所有的value。
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
4、手写简易版HashMap
public class MySimpleHashMap<K, V> {
// 默认初始容量
private final int DEFAULT_CAPACITY = 16;
// 扩容因子
private final float FACTOR = 0.75f;
// 数组大小
private int size;
// 数组
private Node<K, V>[] table;
static class Node<K, V> {
Node<K, V> next;
K key;
V value;
int hash;
Node(int hash, K key, V value, Node<K, V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
public V get(K key) {
if (table == null) {
return null;
}
V val = null;
int hash = hash(key);
int index = hash & (table.length - 1);
Node<K, V> node = table[index];
while (node != null) {
if (isEqual(key, node)) {
val = node.value;
}
node = node.next;
}
return val;
}
public V put(K key, V value) {
return putVal(hash(key), key, value);
}
private V putVal(int hash, K key, V value) {
V oldValue;
int len = table == null ? 0 : table.length;
int index = hash & (len - 1);
if (table == null) {
resize();
}
if (table[index] == null) {
table[index] = new Node<>(hash, key, value, null);
} else {
Node<K, V> node = table[index];
while (true) {
if (isEqual(key, node)) {
oldValue = node.value;
node.value = value;
return oldValue;
}
if (node.next == null) {
node.next = new Node<>(hash, key, value, null);
return null;
}
node = node.next;
}
}
++size;
resize();
return null;
}
private void resize() {
Node<K, V>[] oldTab = table;
int oldCap = table == null ? 0 : table.length;
int newCap;
if (table == null || table.length == 0) {
// 初始化
newCap = DEFAULT_CAPACITY;
} else if (size() > oldCap * FACTOR) {
// 扩容
newCap = oldCap * 2;
} else {
return;
}
Node<K, V>[] newTab = new Node[newCap];
table = newTab;
size = 0;
if (oldTab != null) {
for (int i = 0; i < oldCap; i++) {
if (oldTab[i] == null) {
continue;
}
Node<K, V> node = oldTab[i];
while (node != null) {
put(node.key, node.value);
node = node.next;
}
}
}
}
private boolean isEqual(K key, Node node) {
return node.hash == hash(key) && (node.key == key || (node.key != null && node.key.equals(key)));
}
final int hash(K key) {
int hash;
return key == null ? 0 : (hash = key.hashCode()) ^ (hash >>> 16);
}
public int size() {
return size;
}
}