一 继承关系
推荐文章:1.https://blog.csdn.net/fan2012huan/article/details/51087722
2.https://blog.csdn.net/visant/article/details/80045154
强烈建议!!!!
二 内部结构
先看变量:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16默认初始化容量16
static final int MAXIMUM_CAPACITY = 1 << 30;最大容量 2的30次方
static final float DEFAULT_LOAD_FACTOR = 0.75f;构造函数中没有指定时使用的负载因子。
/*使用树(而不是列表)来设置bin计数阈值。当向至少具有这么多节点的bin添加元素时,bin将转换为树。该值必须大于2,并且应该至少为8,以便与树木移除中关于收缩后转换回普通垃圾箱的假设相吻合*/
static final int TREEIFY_THRESHOLD = 8;这里没看懂
/** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6;
/** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64;
transient Node<K,V>[] table; //节点数组
transient Set<Map.Entry<K,V>> entrySet; 每个元组所存放的集合
transient int size;键值对的大小
transient int modCount;修改数据结构的次数
JavaDoc描述在序列化时为true。此外,如果尚未分配表数组,则此字段保留初始数组容量,或零表示默认的初始\u容量 int threshold;
final float loadFactor;hash table的负载因子
再看下内部类:
1.Node类:
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; } }
2.KeySet类:
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 boolean contains(Object o) { return containsKey(o); } public final boolean remove(Object key) { return removeNode(hash(key), key, null, false, true) != null; } 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(); } } }
3.Values类
final class Values extends AbstractCollection<V> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<V> iterator() { return new ValueIterator(); } public final boolean contains(Object o) { return containsValue(o); } public final Spliterator<V> spliterator() { return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super V> 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.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } }
4.EntrySet类:
final class EntrySet extends AbstractSet<Map.Entry<K,V>> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Node<K,V> candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator<Map.Entry<K,V>> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super Map.Entry<K,V>> 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); } if (modCount != mc) throw new ConcurrentModificationException(); } } }
5.HashIterator 类
abstract class HashIterator { Node<K,V> next; // 下一个要返回的元组 Node<K,V> current; // 当前元祖 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); } } public final boolean hasNext() { return next != null; } 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; } 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; } }
三 自身实现的方法
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); } static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } /** * Returns x's Class if it is of the form "class C implements * Comparable<C>", else null. */ static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) { Class<?> c; Type[] ts, as; Type t; ParameterizedType p; if ((c = x.getClass()) == String.class) // bypass checks return c; if ((ts = c.getGenericInterfaces()) != null) { for (int i = 0; i < ts.length; ++i) { if (((t = ts[i]) instanceof ParameterizedType) && ((p = (ParameterizedType)t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) // type arg is c return c; } } } return null; } static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); } static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); } /**返回 大于输入参数且最近的2的整数次幂的数,算法解释:https://www.cnblogs.com/loading4/p/6239441.html 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; } final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); //得到所有键值对的数量 if (s > 0) { if (table == null) { // 如果桶还未初始化 float ft = ((float)s / loadFactor) + 1.0F; //size除装载因子得到容量大小 int t = ((ft < (float)MAXIMUM_CAPACITY) ? //判断计算出的容量大小会不会超过最大容量 (int)ft : MAXIMUM_CAPACITY); if (t > threshold) 如果容量大小超过扩容阈值,则进行扩容 threshold = tableSizeFor(t); } else if (s > threshold) //如果map的size大于扩容阈值,则进行扩容 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); } } } final Node<K,V> getNode(int hash, Object key) { //桶数组,通过hash值进行位运算找到桶,当前的节点,桶数组的长度,当前e节点的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 { //如果还是链表就通do-while查询 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } //也可以看详细的图介绍,从上面的文章里面找的 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { //table数组的引用,通过hash定址找到的桶节点,table长度,hash定址用的下标 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)//如果通过hash不能找到一个桶,则直接存入这个键值对 tab[i] = newNode(hash, key, value, null); else { //如果通过hash找到了桶的情况:要么就是没有对应的Key直接进行插入;要么就是找到了同样key的键值对,则需要替换值 Node<K,V> e; K k; //需要处理的当前节点,当前节点的key if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))//如果桶数组的第一个节点就是同样的key则直接将p作为要处理的e,交由下面的if换值方法处理 e = p; else if (p instanceof TreeNode) //如果头结点是一个红黑树类型的,则通过专有的方法进行 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //如果不是以上两种情况,只有遍历链表了,还有可能出现相同的key,但是这里遍历的过程中会记录节点的个数,如果超过的“树化”阈值,则需要进行转化。 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))))//这里是找到同样key的节点,则需要中断方法,同时交由下面的换值方法处理了 break; p = e; } } if (e != null) { // existing mapping for key //换值方法判断e是不是存有上面过程下来保留的要处理的e V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) //换值 e.value = value; afterNodeAccess(e); return oldValue; //返回旧值 } } ++modCount; //修改次数++ if (++size > threshold) //判断需不需要扩容 resize(); afterNodeInsertion(evict); return null; } //扩容大小 推荐文章:https://blog.csdn.net/weixin_39667787/article/details/86678215 final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; 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) 如果桶数组不存在或size为0,则初始化容量为Threshold 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<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; 将当前数组置空 if (e.next == null) 如果当前桶数组后面没有链表或树就重新计算hash值索引 newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order 相比于jdk7来说优化了算法,维持了链表的顺序 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; } //转化为红黑树的算法,这里暂且先看下。。。 final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> 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); } } final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node<K,V> 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<K,V>)p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; }
详细原理推荐,强烈推荐:https://blog.csdn.net/weixin_39667787/article/details/86678215