1. 基本结构
HashMap
的核心是一个数组,每个数组元素是一个链表或红黑树(JDK 1.8 及以后)。当哈希冲突发生时,链表或红黑树用于存储多个键值对。
// HashMap的基本结构
public class HashMap<K, V> extends AbstractMap<K, V>implements Map<K, V>, Cloneable, Serializable {// 默认初始容量为16static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16// 最大容量为2^30static final int MAXIMUM_CAPACITY = 1 << 30;// 默认加载因子为0.75static 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 Node<K, V>[] table;// 存储具体键值对的集合transient Set<Map.Entry<K, V>> entrySet;// 存储的键值对的数量transient int size;// 扩容和其他结构修改次数transient int modCount;// 阈值int threshold;// 加载因子final float loadFactor;// Node 是 HashMap 的基本结构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. 哈希算法
HashMap
使用的哈希算法通过扰动函数减少哈希冲突,提高查找效率。
static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这个方法对键的哈希码进行高低16位混合,以增加随机性,减少冲突。
3. 初始化和扩容
HashMap
在插入元素时,会检查当前容量是否需要扩容,如果需要,就进行扩容。扩容时,新容量是旧容量的两倍。
// 初始化
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);
}// 扩容
final Node<K, V>[] resize() {Node<K, V>[] oldTable = table;int oldCap = (oldTable == null) ? 0 : oldTable.length;int oldThr = threshold;int newCap, newThr = 0;if (oldCap > 0) {if (oldCap >= MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return oldTable;}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 thresholdnewCap = oldThr;else { // zero initial threshold signifies using defaultsnewCap = 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>[] newTable = (Node<K, V>[])new Node[newCap];table = newTable;if (oldTable != null) {for (int j = 0; j < oldCap; ++j) {Node<K, V> e;if ((e = oldTable[j]) != null) {oldTable[j] = null;if (e.next == null)newTable[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K, V>)e).split(this, newTable, j, oldCap);else { // preserve orderNode<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;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);if (loTail != null) {loTail.next = null;newTable[j] = loHead;}if (hiTail != null) {hiTail.next = null;newTable[j + oldCap] = hiHead;}}}}}return newTable;
}
4. 插入元素
插入元素时,首先计算元素的哈希值,然后确定存储位置。如果发生哈希冲突,将元素链入当前链表或红黑树中。
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) // -1 for 1sttreeifyBin(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 keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;