jdk源码-HashMap
AbstractMap
AbstractMap是Map接口的抽象实现类,通过抽象方法keySet()
实现了get(key)
,remove(key)
,containsKey(key)
,containsValue(value)
的基本算法,遍历加equals。
HashMap
HashMap是AbstractMap的一个实现类,1.8之后对其进行了重写,加入TreeNode的结构,原因是存在使用不当的hashcode导致许多key都是用共同的hashcode,在大量数据的情况下,效率慢。于是切到TreeNode结构。只有重写hashCode不当会导致这一个情况。
结构:数组 +(链表/红黑树)
方式:indexOf定位数组下标,根据下标链表+
扩容条件:当hashMap的数据到警戒值 size*0.75,就会扩容,数组*2
构造方法:阀值默认0.75f
hashMap构造后,并不会新建数组tab,只会赋值阀值因子,它是懒加载,只有在第一次插入值的时候加载一个长度为16的数组。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
get(key):对key做一个hash处理,得到的hash值进行(tab.length - 1) & hash
来获得数组index,判断数组的第一个Node是否为TreeNode类型,是-调用getTreeNode()
,不是,遍历链表Node,判断key的hashCode与equlas。
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;
}
注意一下hash算法,如果key是null,会转成0,但是key是通过equals来比较是否相同的,所以hashMap key不可为空。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
put(key,object)
:hashMap的put(key)
是一个比较复杂的算法,流程是这样的判断链表是否存在,不存在resize()
,新建一个长度为16,阀值系数为0.75的hashMap;存在取得hash(key)并通过公式(tab.length - 1) & hash
来获得数组index,判断数组tab[index]元素是否存在,不存在直接插入;存在判断是否为TreeNode,是TreeNode就安TreeNode的方法插入;不是就遍历链表,如果不存在key相同,就插入末尾,否则替换;判断该链表长度,如果大于8,就直接转出TreeNode;节点数加一并判断是否超过阀值,如果超过就resize()
;resize()
会把数组扩容为double,遍历老tab中的数组每一项;如果是treeNode,就按treeNode的方法重写定位;如果不是,遍历链表所有元素,如果满足公式(e.hash & oldCap) == 0
,就把该元素放到新tab的原index,如果不满足,则把该元素放到新tab的原index加原tab.length的位置,新的元素都插入在链表尾。
注意:在1.8的HashMap中,因为put放入的是尾节点,且resize()也是放尾节点,就算同时两个线程put并resize(),也不会出现循环链表,只会出现put遗漏的情况。而1.7的hashMap存在出现循环链表的情况。
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;
// 如果数组index的项为空,直接赋值
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 如果第一个元素的key与插入key相同,直接替换
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果是TreeNode,走putTreeVal方法
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 遍历链表
for (int binCount = 0; ; ++binCount) {
// 如果到了链表尾还没有相同的key,就将key和value构造成新元素并插入链表尾。
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果链表长度超过8,链表转红黑数
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;
}
}
// 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;
}
// 初始化hashMap 或 扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 如果原hashMap的tab不为空,扩容为之前两倍。
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//tab为空
else { // zero initial threshold signifies using defaults
// 如果原tab为空,新建数组,长度16,阀值16*0.75
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 创建新数组newTab
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// 遍历老数组,并把元素发到新数组
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 如果数组该index只有一个元素,放到新数组的`e.hash & (newCap - 1)`下。
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 如果数组元素是TreeNode,走TreeNode的split方法
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 遍历链表所有元素,如果满足公式(e.hash & oldCap) == 0,就把该元素放到新tab的原index的链表末尾,如果不满足,则把该元素放到新tab的原index加原tab.length的链表末尾
else {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
keySet():key用于遍历所有Map元素,HashMap通过内部类实现Set接口
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
//先遍历数组,接着遍历数组每一项的所有的链表数据
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
// 通过两个元素,next和current来迭代,返回current,判断next。
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
}