1.HashMap的底层数据结构?
看源码:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
//注意此处的Next
Node<K,V> next;
。。。。。
}
transient Node<K,V>[] table;//声明了一个Node数组,名为table.
从上面的源码中我们可以看到,Entry实体为一个Node节点,而同时存在一个Node数组,显而易见,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;
//threshold计算最大容量,当size大于这个值时,将会是hashmap的空间扩大两倍
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);//默认装载因子值为0.75F
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
* 默认未指定的hashmap的容量为16
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
上面是关于hashmap的构造函数,默认capacity以及装载因子。
2.put操作
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//我们看hash函数,因为hashmap允许 为null的key,可以看到,当key为null时,hash值为0。否则进行高位运算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//重点看put的具体操作:
/**
* @param onlyIfAbsent 如果取值为TRUE,那么你使用相同的key,put value,后面的value将不会覆盖第一次的value
* @param evict 如果取值为FALSE,那么table(就是前面的Node数组)将会进入创建模式
*/
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;
}
在执行putVal方法时,
首先进行判断 table(Node数组)是否被创建,如果未创建则resize(),里面会默认为table分配16个空间。
然后计算hash值对应的table位置是否为null(是否发生碰撞),未发生碰撞则成功放入元素,modCount(修改次数加一),再判断此时的size是否大于了threshold(capacity*load-factor)。大于则扩大map的capacity并对其中的元素进行重新hash。
在前一步如果发生碰撞,则会遍历此处的node链表,(对于hashmap的子类,LinkedHashMap,是遍历其二叉树)。如果key存在,那么将旧的value覆盖掉,但不会改变key。
如果不存在key,就新建节点,放在链表的尾部。同样执行后续的modCount++等操作。
3.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) {
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;
}
首先判断hashmap是否为null,并且其内有node节点存在,同时我们输入的key计算出来的hash值对应在table中存在不为空,那么将进行下一步的查找,否则,将直接返回null。
由于第一步的检测,在table中存在key的hash值对应的元素,始终先检查第一个元素的key是否等于我们输入的key(hashmap中不可能避免碰撞,所以不同的key有可能在相同的table位置,所以延伸出node链表)。如果与第一个不等,LinkedHashMap就访问像一个树节点,hashmap将访问下一个Node节点,继续判断。直到找到,或者到达链表末尾,最终返回对应的node或者null。
fail-fast
还记得modCount嘛?它是记载map的修改次数的,同时也是实现快速失败机制的基础。
HashIterator() {
expectedModCount = modCount;//迭代器构建时,就将此刻的modCount赋值给expectedModCount
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) {
do {} while (index < t.length && (next = t[index++]) == null);
}
}
//在后续的迭代器操作中,都存在该代码,此时的modCount是volatile的(线程间修改可见):
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
这就是快速失败机制的实现,但是对于并发编程来说,我们应该使用它来验证错误。
当然你肯定知道,使用remove方法不会触发快速失败。
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;//remove之后会将modCount重新赋值给expectedModCount
}
笔者第一次对源码进行研究,如有错误的地方,欢迎大家给出建议,谢谢。