首先要记住核心, HashMap的底层是数组+单向链表, 超过THRESHOLD设定的值 对应的数组下标下的链表会转换成红黑树(但是将链表转换成红黑树前会判断,如果当前数组的长度小于 64,那么会选择先进行数组扩容,而不是转换为红黑树)
没有深入了解红黑树 但是不影响看代码 有关tree的就是涉及到红黑树的
删了很多的简单的代码、总体看下来官方代码就是清晰,认真看完一个其他发现其实也差不多
一定要根据数据结构去看
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; //初始容量 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 // 最大值 超过20亿 static final int MAXIMUM_CAPACITY = 1 << 30; // 超过容量* LOAD_FACTOR 就会扩容 (16 和 0.75 肯定是经过大量计算得出的) static final float DEFAULT_LOAD_FACTOR = 0.75f; //单个链表长超过就会转换成红黑树 static final int TREEIFY_THRESHOLD = 8; //从树转换回来 static final int UNTREEIFY_THRESHOLD = 6; //hashMap中元素数量大于64时,也会转为红黑树结构。 static final int MIN_TREEIFY_CAPACITY = 64;//就是链表中的每个节点 static class Node implements Map.Entry { final int hash; final K key; V value; Node next; Node(int hash, K key, V value, Node next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } 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; } } static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } //返回最接近的2的幂次方 static final int tableSizeFor(int cap) { }//就是存储节点和链表的数组(数据存放的地方) transient Node[] table; //用于转换进行迭代 transient Set> entrySet; //元素的数量 transient int size; //结构改变的次数 transient int modCount; // 决定何时绝定扩容 int threshold; final float loadFactor;//四种构造方法 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); } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } //将Map集合放入 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); if (s > 0) { if (table == null) { // pre-size float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); } else if (s > threshold)//判断是否扩容 resize(); for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } }// 查找对应的key的value public V get(Object key) { Node e; return (e = getNode(hash(key), key)) == null ? null : e.value; } //查找key对应的node final Node getNode(int hash, Object key) { Node[] tab; Node first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // 盲猜通过tab[(n - 1) & hash]找到是哪个数组下标 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)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; } public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } // 放入节点值或者更新节点值的方法 //第四个参数表示如果该key存在值,如果为null的话,则插入新的value final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node[] tab; Node p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null)// 对应的数组下标没有值才插入 否则p就是对应的下标的头结点 tab[i] = newNode(hash, key, value, null); else { Node 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)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; } //扩容函数 final Node[] resize() { Node[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) {// 扩容为int的最大或者扩容两倍 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) // 如果扩容因子被初始化了就更换 newCap = oldThr; else { // 代表使用默认的 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;//根据上面不同的情况判断后进行跟新 @SuppressWarnings({"rawtypes","unchecked"}) Node[] newTab = (Node[])new Node[newCap];//扩容 table = newTab; //把就数组遍历到新的数组中 并把旧数组置为null 释放内存 if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode)e).split(this, newTab, j, oldCap); else { // preserve order 把对应数组下的链表更新过去 Node loHead = null, loTail = null; Node hiHead = null, hiTail = null; Node 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; } // 进行扩容或者 更换转换成树 final void treeifyBin(Node[] tab, int hash) { int n, index; Node e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//扩容 resize(); else if ((e = tab[index = (n - 1) & hash]) != null) {//转换成红黑树 TreeNode hd = null, tl = null; do { //循环链表, 把节点转换成树叶子 TreeNode p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } } public V remove(Object key) { Node e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } // value为值代表可以直接删除,不然需要先进行查找 match表示只有value相等时才能删除, movable表示删除后是否移动节点 final Node removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node[] tab; Node p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { //找到要删除key节点对应的数组下标 Node node = null, e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))//先看头结点是否满足 node = p; else if ((e = p.next) != null) { if (p instanceof TreeNode) // 检查是否是树叶子 node = ((TreeNode)p).getTreeNode(hash, key); else {//遍历进行查找 do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; // node是要删除的节点 break; } p = e; //p是要删除的节点的上一个节点 } while ((e = e.next) != null); } } //正常!matchvalue表示不用判断值 if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode)node).removeTreeNode(this, tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; afterNodeRemoval(node);//此方法在hashMap中是为了让子类去实现,主要是对删除结点后的链表关系进行处理 return node; } } return null; } public void clear() { Node[] tab; modCount++; if ((tab = table) != null && size > 0) { size = 0; for (int i = 0; i < tab.length; ++i) tab[i] = null; } } public boolean containsValue(Object value) { Node[] tab; V v; if ((tab = table) != null && size > 0) { for (int i = 0; i < tab.length; ++i) { for (Node e = tab[i]; e != null; e = e.next) { if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false; }
//这三个方法表示的是在访问、插入、删除某个节点之后,进行一些处理,它们在linkedHashMap都有各自的实现(就是子类会根据需要进行设计) // Callbacks to allow linkedHashMap post-actions void afterNodeAccess(Node p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node p) { }