本人最近研究HashMap的源码,并写下这篇文章进行记录。
目录
1.HashMap的数据结构
个人认为学习集合的源码,先要知道集合的底层数据结构及实现原理,才能根据原理更好的读懂代码的逻辑。所以首先是了解HashMap的实现原理。在JDK1.8后HashMap的实现由数组+单向链表转化为了数组+单向链表+红黑树,如下图所示是JDK1.8HashMap的底层实现方式。
首先是第一部分Hash桶数组(Table),这个是HashMap的主体,里面存放的元素是Node<K,V>内部类对象,键(key)经过hash函数计算得到的结果作为地址去存放Hash桶中。了解Hash算法的了都会知道key的hash结果难免会发生hash冲突,冲突了之后后续的元素链接到hash槽位的第一元素后面形成链表。当链表长度大于8之后,就将链表转换成红黑树。以上就是我总结的Hash数据结构的实现。至于Hash桶的扩容;链表和红黑树的转换等问题在后续解读代码时做详细说明。
2.HashMap 构造函数
重点代码块如下:
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;
//如果指定了初始容量参数作为容量则Hash会选择一个大于该数字的第一2的幂作为容量
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Returns a power of two size for the given target capacity.
*/
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;
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
2.1HashMap的初始化参数
在HashMap的源码中有一下几个关键参数,扩容的详细代码在put章节会具体解析
-
Capacity
-
容量,表示这个HashMap能装多少键值对,现有逻辑是当 size > capacity * loadFactor 时则进行扩容
-
//默认的初始化容量 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
-
如果指定了初始容量参数作为容量则Hash会选择一个大于该数字的第一个2的幂作为容量。例如 1->2、3->8、9->16
-
//这个方法就是用获取指定容量参数的第一个2的幂 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; }
-
这里有一个小建议:在初始化HashMap的时候,应该尽量指定其大小。尤其是当你已知map中存放的元素个数时。(《阿里巴巴Java开发规约》)
-
-
size
-
这个字段用于记录map中存放的键值对数量
-
-
final float loadFactor
-
负载系数,用来衡量HashMap负载量的程度。
-
//默认的负载系数即3/4 static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
一般不建议修改负载系数,因为容量是2的幂,所以capacity * loadFactor总是整数
-
-
threshold;
-
临界值,当实际KV个数超过threshold时,HashMap会将容量扩容,threshold=容量*加载因子
-
了解了以上几个参数之后,就知道构造函数其实只是设置了HashMap的一些参数,没有具体的进行初始化。具体的初始化在Put方法中进行。
3.put方法解析
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//计算Hash值默认方法
static final int hash(Object key) {
int h;
//这段代码将key的hashcode进行处理,均匀的将哈希值分布在低16位与高16为中,减少hash碰撞
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断Hash桶是否创建.没有则创建
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;
3.1Node<K,V> 内部类
**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
}