1.HashMap源码阅读目标
了解具体的数据结构(hash及冲突链表、红黑树)和重要方法的具体实现(hashCode、equals、put、resize...)
2.重要方法
hashCode 与 equals都是在AbstractMap中定义的
hashCode是各元素hash的累加 h += iter.next().hashCode();
equals 1.是否是本身; 2.是否是Map实例; 3.size是否相等; 4.比较每个value
重点在于put、resize具体实现步骤:
put:
1.tab为null或length为0 重新resize
2.位置hash(key) & (n-1)的元素为null,则直接赋值
3.既然对应位置的元素不为null,则要看它有什么类型(单个元素(hash无冲突)或红黑树或链表)
单个元素(新的元素如果与这个元素不相等)则要转为链表,链表则可能转为红黑树(转化规则 >= 7)
++modCount
4.++size > threshold 则resize()
remove类似(<=6则转化为链表)
1 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, 2 boolean evict) { 3 Node<K,V>[] tab; Node<K,V> p; int n, i; 4 if ((tab = table) == null || (n = tab.length) == 0) 5 n = (tab = resize()).length; 6 if ((p = tab[i = (n - 1) & hash]) == null) 7 tab[i] = newNode(hash, key, value, null); 8 else { 9 Node<K,V> e; K k; 10 if (p.hash == hash && 11 ((k = p.key) == key || (key != null && key.equals(k)))) 12 e = p; 13 else if (p instanceof TreeNode) 14 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); 15 else { 16 for (int binCount = 0; ; ++binCount) { 17 if ((e = p.next) == null) { 18 p.next = newNode(hash, key, value, null); 19 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 20 treeifyBin(tab, hash); 21 break; 22 } 23 if (e.hash == hash && 24 ((k = e.key) == key || (key != null && key.equals(k)))) 25 break; 26 p = e; 27 } 28 } 29 if (e != null) { // existing mapping for key 30 V oldValue = e.value; 31 if (!onlyIfAbsent || oldValue == null) 32 e.value = value; 33 afterNodeAccess(e); 34 return oldValue; 35 } 36 } 37 ++modCount; 38 if (++size > threshold) 39 resize(); 40 afterNodeInsertion(evict); 41 return null; 42 }
treeifyBin:
链表转为红黑树,红黑树较为复杂,所以将单独另起一篇仔细研究学习
keySet/entrySet:
1 new KeySet(); 2 forEach: 3 int mc = modCount; 4 for (int i = 0; i < tab.length; ++i) { 5 for (Node<K,V> e = tab[i]; e != null; e = e.next) 6 action.accept(e.key); 7 } 8 if (modCount != mc) 9 throw new ConcurrentModificationException();