HashMap的原理就是用一个数组存储一系列 K-V 结构的 Node 实体,存储位置通过对 key 的 hashCode 计算得到,Node 对象有 next 指针,作为单链表的一个节点。如果发生 hash 冲突,就将新的 Node 插入链表里。链表过长超过阈值的话为了提高查询效率会转为红黑树(JDK 1.8以后)。
成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
transient int size;
int threshold;
transient Node<K,V>[] table;
|
hashMap默认初始化长度是多少?为什么是这么多?
默认初始化长度是 1<<< 4,之所以不直接写16,是因为位运算比算术运算效率高,之所以选择16,是为了服务与 index 的计算公式 index = hash & (length - 1)(这里采用与运算和取模的效果一样,但性能更好),初始化长度减1后为15,二进制位1111,和 hash 值运算后的结果等同于 hash 后几位的值,只要 hash 值本身分布均匀,那 hash 算法的结果就是均匀的,从而实现均匀分布。
为什么树化标准是8个?
在源码注释中有提到:如果 hashCode 分布良好的话,很少出现链表比较长的情况。理想情况下,链表的长度符合泊松分布。各长度的概率如下
当链表长度为8时,概率为0.00000006,概率非常小,红黑树的转换基本不会发生。当然也会有用到:用户使用自己的 hash 算法,导致 hashCode 分布离散很差,链表很长的情况。
为什么树退化为链表的阈值是6个?
增加一个过渡,防止在临界值时增加/删除一个元素时,在树和链表之间频繁的转换,降低性能。
初始化方法
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; }
public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); }
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(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }
|
hash方法
hash() 方法是 HashMap 的核心方法,算出 key 的 hashCode 后,将算出的结果右移16位,与原 hashCode 按位异或得到 hash 后的值,
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
|
为什么要右移16位?
让 hashCode 的高16位也参与运算,增加扰动,减少碰撞冲突,因为大部分元素的 hashCode 在低位是相同的。
相关问题:String的hashCode的实现?
public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
|
简单来说就是给字符串的每一位,按位乘31的n次幂,再相加,用自然溢出来等效取模。选择31因为这个质数不大不小,且可以被虚拟机优化,运算效率更高。i*31 = i*(32-1) = i<<5-1
put方法
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; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> 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<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) treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
|
在 putVal 方法中为什么要用 i = (n-1) & hash
作为索引运算呢?
这其实是种优化手段,由于数组的大小永远是一个2次幂,在扩容后,一个元素的新索引要么在原位置,要么在原位置+扩容前的容量。这个方法的巧妙处全在于&运算,&运算只会关注 n-1(n=数组长度)的有效位,当扩容后,n的有效位相比之前会多增加一位(n会变成之前的两倍,所以确保数组长度永远是2次幂很重要),然后只需要判断 hash 在新增的有效位的位置是 0 还是 1 就可以算出新的索引位置,如果是 0,如果是 2,索引就是原索引+扩容前的容量。
resize方法
resize()方法主要是用来扩容,具体操作是新建一个hash表,然后将旧表中的内容重新散列复制到新表中。源码主要分为2部分:
- 第一部分主要用于判断当前操作的类型(初始化or扩容)并且计算出新生成的表的容量和阈值。
- 第二部分只用于扩容操作时,将旧表中的元素重新散列放入新表。
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; } 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<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; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); 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; }
|
get方法
get 方法逻辑比较简单,直接看注释
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 && ((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; }
|
remove方法
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; 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; }
|