HashMap作为日常开发中,常用的数据类型,给开发带来了很多的便利。但是为了不做一个只用调用API的码农,理解HashMap的实现也是很有必要的。
本文讲解的是 JDK1.8 中的HashMap,相对于之前的版本,JDK1.8中最大的改变就是数据存储的方式。
1.8之前如果产生 hash冲突,解决办法是使用链表,但是如果 hash冲突严重的话,get() 方法的时间复杂度会从O(1)变成 O(n) ;1.8之后加入了 红黑树,当冲突的数据较少时,仍然使用 链表 ,较多时则改用 红黑树 。
HashMap接收一个键值对作为存储内容,在定义时需要指定泛型,也是为了数据存取的安全。
Map<String, String> m = new HashMap<>();
//or
HashMap<String, String> m = new HashMap<>(5);
HashMap的构造函数:
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(int initialCapacity) {
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);
}
当调用无参构造时,加载因子 loadFactor 为默认值 0.75f 。
什么是加载因子?HashMap是基于数组和链表及红黑树构建的,当添加键值对时,会占用数组的空间,假设默认的数组大小为 16 ,16 * 0.75 = 12,当添加的元素数量大于等于12时,会重新新建一个更大数组存放元素以及rehashing(再哈希)。当然这也是一个费事的操作,所以应该根据需求,确定初始容量。这就用到了 HashMap(int) 构造函数。
HashMap(int) 给一个 int 类型的参数,作为初始容量大小,HashMap(int) 中再次调用 HashMap(int, float)构造函数。第一个为 初始容量 ,第二个为 加载因子 。再看 HashMap(int, float) 。
当传入的 初始容量 小于 0 ,抛出 IllegalArgumentException 异常,而且容量最大为 1<<30 即 1073741824 ,加载因子 小于等于 0 ,或者是一个非数字(NaN),同样抛出 IllegalArgumentException 异常;如果两个参数都合法,则初始化成功。
有趣的是,最后一行代码: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;
}
对于传入的 初始容量 的赋值,是调用 tableSizeFor(int) 方法的返回值,而不是我们指定的大小。假如我们这样:
// 初始容量为 10 , 加载因子为 0.7
Map<String, Object> map = new HashMap<>(10, 0.7f);
我们指定初始容量为 10 ,但是经过 tableSizeFor(int) 方法之后,返回值变为 16 ,刚好为 2 的整数次方。即初始容量为16。这是为什么呢?毋庸置疑,这样做一定是为了优化,也就是提高效率。在 putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) 方法中。当添加元素时,利用hash与容量做与运算。tab[i = (n - 1) & hash] ,n 为数组的大小,即HashMap的容量,也就是 2的整次幂,假设 n = 16,16 - 1 的二级制码为 1111 与 hash 做 与运算时,效率会特别高,所以HashMap的容量为 2的整次幂。
putVal() 方法如下:
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) //hash未冲突则新建节点
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash && //当key相等时,替换value,并返回旧value
((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) { // 当key存在
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //当元素个数大于阈值,即size > capacity * DEFAULT_LOAD_FACTOR
resize();
afterNodeInsertion(evict);
return null;
}
其中有几个重要的成员变量:
// 默认初始容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量,即 1073741824
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// threshold = capacity * DEFAULT_LOAD_FACTOR
int threshold;
再来看 get() 方法:
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) { //根据哈希值得到位置索引,如果存在且key相等,直接返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) { //hash冲突,1.8之后用链表和红黑树解决哈希冲突,当 first 是 TreeNode 类型时,从树中查找元素
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;
}