HashMap
学习了一下HashMap的源码,分享出来,欢迎大佬指正。
参数及其解释(这里的容量其实就是HashMap桶的数量,也就是数组的大小):
- 初始化容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
- 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
- 默认负载因子
当容量大于当前容量和负载因子的乘积后,HashMap扩容,扩容为当前容量的2倍
static final float DEFAULT_LOAD_FACTOR = 0.75f;
- 链表最大长度
此参数只有JDK1.8之后出现,JDK1.8开始解决哈希冲突的方式转变为链表加红黑树,当链表长度大于等于8时变为红黑树
static final int TREEIFY_THRESHOLD = 8;
- 红黑树最少节点数
也是JDK1.8之后出现,当红黑树的节点数小于6个时变为链表
static final int UNTREEIFY_THRESHOLD = 6;
- 使用红黑数的最小容量
只有当HashMap的容量大于等于64时才会使用红黑树处理冲突,否则会用扩容机制
static final int MIN_TREEIFY_CAPACITY = 64;
一些方法:
-
取哈希值函数
这里取哈希值函数就不用太过纠结了,看一下对比:- JDK1.8
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }- JDK1.7
final int hash(Object k) { int h = 0; if (useAltHashing) { if (k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h = hashSeed; } h ^= k.hashCode(); // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } -
现在我们开始分析JDK1.8下的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) // -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; }这里先忽略掉resize()方法的具体实现,先看put方法。
table其实就是HashMap中的数组。- 首先是判断了容量是否为0,即HashMap是否为空,为空的话就resize()。
- 然后判断数组该位置上是否有值,即是否发生了哈希冲突,没有发生冲突,直接newNode()放在这个位置。
- 然后就是一般情况(发生了哈希冲突)。此时先判断是否和发生冲突的节点key是否相等,如果相等,说明是同一个,修改即可。接下判断是否是树上的节点,如果是,则执行添加到树的操作。再接下来就是一般情况,遍历链表,如果遇到key相等的节点退出,遍历到尾部后添加到链表尾部,并根据链表节点数判断是否要变成红黑树。最后再判断是否要修改已经存在的值,这里是修改的,返回旧值。最后才是判断是否需要扩容的操作。
-
再来看一下扩容方法
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) // 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 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; }这里大概描述一下逻辑:
如果原数组长度大于0,则判断是否已经扩容到最大值,如果扩容到最大值,将扩容参数设置为最大整数,即为永不扩容,否则将扩容参数扩大两倍。 如果原数组长度等于0的话那就做初始化。然后设置新的扩容参数。
接下来就是真正的扩容,遍历旧数组,如果位置只有一个节点,则直降将节点放到新数组的对应位置,如果不止一个节点,就判断每个节点的哈希最高位是否为0,为0的话直接放入新数组对应位置,否则就放入新数组对应位置加旧数组的长度之后的位置。(这里还有关于树的分割,就不分析了)。