数组+链表/红黑树,红黑树是java8的改进。
HashMap是非线程安全的,所有多个线程同时写入会有问题,适用于单线程写,多线程读的场景。 ConcurrentHashMap可以解决线程安全的问题。
// 默认初始容量 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; final float loadFactor;
// 取值是:(int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 当 ++size>threshold 时,会进行扩容 int threshold;
// 当链表长度大于8,链表会变成红黑树 static final int TREEIFY_THRESHOLD = 8;
是一个Node的数组
/** * The table, initialized on first use, and resized as * necessary. When allocated, <font color=red> length is always a power of two.</font> * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table; 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; } }HashMap使用链接法,当链表长度大于8会升级为红黑树。
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; // i = (n - 1) & hash获取数组下标,并且所在下标没有数据 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 { // 这里遍历链表,超过TREEIFY_THRESHOLD,变换成红黑树,找出要插入(这里是链表结尾)还是更新 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; }这里扩容的过程是rehash,自然而然要涉及到数据迁移。比较简单的方案是,数组扩大一倍,然后计算每一个元素新的位置进行调整,但是这样效率很低。
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; } // 这里翻倍了,新的newCap = oldCap << 1,这里很关键 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; else { // zero initial threshold signifies using defaults 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 { // preserve order // 这里是链表数据高效迁移,是一整套设计。 // 首先newCap = oldCap << 1,新的容量总是老的两倍,并且总是2的倍数 // 老的节点去计算索引时,总是在 原地 或者 newTab[j + oldCap] // 这个设计真的很巧妙 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; }在HashTable中,initialCapacity的默认值是11,取了素数。而HashMap没有取素数,而是取了合数,并进行了一整套的设计,更高效。
最坏的情况 是所有节点都到了 一个链表里面,时间复杂度O(n)
h(k) = k mod m
h(k) = m(kA mod 1) 0<A<1,取kA mod 1的小数部分