HashMap源码浅析(jdk1.8)
HashMap是以key-value键值对的形式进行存储数据的,数据结构是以数组+链表或红黑树实现。
数据结构图如下:
一、关键属性
HashMap初始化和方法使用的属性。
/** * 默认初始容量16(2的4次方) */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * 最大容量(2的30次方) */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默认加载因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * 链表节点数大于8变成红黑树 */ static final int TREEIFY_THRESHOLD = 8; /** * 红黑树节点数小于6变成链表 */ static final int UNTREEIFY_THRESHOLD = 6; /** * 在变成红黑树前判断键值对的数量是否小于64 */ static final int MIN_TREEIFY_CAPACITY = 64;
二、构造方法
1、HashMap(int initialCapacity, 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); } 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; }
2、HashMap(int initialCapacity)调用第一个构造方法。
public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); }
3、HashMap(Map<? extends K, ? extends V> m),把参数map集合初始化到新集合中。
public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } 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); } } }
4、HashMap()方法只初始化加载因子。
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
三、主要方法
1、put(K key, V value)方法,先通过计算hash来判断新元素所在节点数组的位置,
如果位置为空则直接添加新元素放在数组节点上,如果不为空则在通过hash和key来判断新添加的元素是否
和在此数组节点上的元素有相同的key,相同则覆盖,否则在判断此节点是树节点还是普通节点,
树节点则进入红黑树的添加,普通节点进入链表的添加,链表通过循环来判断新节点是覆盖还是在尾部添加,
还是超出8个节点变成红黑树添加。
// 添加元素或覆盖元素 public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } // 计算hash值,即元素所属的数组位置 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; // 如果table为初始化或长度为0,则扩容 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; // 如果添加的节点和原有的key相同则覆盖 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 如果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; } // hash和key相同退出循环 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; }
2、resize()方法,对原map集合进行扩容,容量变为原来2倍。
final Node<K,V>[] resize() { // 保存当前数组节点 Node<K,V>[] oldTab = table; // 保存原数组节点大小 int oldCap = (oldTab == null) ? 0 : oldTab.length; // 保存当前阀值 int oldThr = threshold; // 声明新数组节点大小和阀值 int newCap, newThr = 0; // 原map有值 if (oldCap > 0) { // 原map元素个数已达到最大值 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 原map容量2倍小于最大值且原map容量大于等于16则扩容 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; // 只调用HashMap()进这个 else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } // 新阀值为0(只进行初始化) 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) newTab[e.hash & (newCap - 1)] = e; // e为红黑树节点 else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); // e为普通节点 else { // preserve order 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; }
3、remove(Object key)方法,根据key删除元素。
// 根据key删除元素 public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } 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; // map集合不为空 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; }
4、get(Object key)方法,根据key查找元素。
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; // map集合不为空 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; }