数组+链表+红黑树
构成哈希碰撞
就以链表的形式存储,当链表过长的话,HashMap会把这个链表转换成红黑树来存储public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { //默认初始容量为16 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //最大容量 static final int MAXIMUM_CAPACITY = 1 << 30; //默认负载因子为0.75 static final float DEFAULT_LOAD_FACTOR = 0.75f; //Hash数组(在resize()中初始化) transient Node<K,V>[] table; //ket-value集合 transient Set<Map.Entry<K,V>> entrySet; //元素个数 transient int size; //修改次数 transient int modCount; //容量阈值(元素个数超过该值会自动扩容) int threshold; //负载因子 final float loadFactor;
总结node
16
,默认负载因子为0.75
threshold = 数组长度 * loadFactor
,当元素个数超过threshold(容量阈值)时,HashMap会进行扩容操做/*无参*/ 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); }
能够看到容量阈值threshold是由tableSizeFor(initialCapacity)计算出来的,咱们来看看具体实现:算法
/*找到大于或等于 cap 的最小2的幂,用来作容量阈值*/ 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; }
tableSizeFor(int cap)其实就是找到大于或等于cap的最小2的幂
,用来作容量阈值。
这个算法的思路就是将该数字的最高非0位后面全置为1!最后将结果+1后能够获得最小的二的整数幂。
一开始进行减一的操做是为了防止当cap为二的整数幂时,没有把自身包含进范围!segmentfault
当前桶数组长度的2倍进行扩容,阈值也变为原来的2倍
。扩容以后,要从新计算键值对的位置,并把它们移动到合适的位置上去。以上就是 HashMap 的扩容大体过程,接下来咱们来看看具体的实现:数组
/*扩容*/ final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; //一、若oldCap>0 说明hash数组table已被初始化 if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; }//按当前桶数组长度的2倍进行扩容,阈值也变为原来的2倍 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; }//二、若数组未被初始化,而threshold>0说明调用了HashMap(initialCapacity)和HashMap(initialCapacity, loadFactor)构造器 else if (oldThr > 0) newCap = oldThr;//新容量设为数组阈值 else { //三、若table数组未被初始化,且threshold为0说明调用HashMap()构造方法 newCap = DEFAULT_INITIAL_CAPACITY;//默认为16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//16*0.75 } //若计算过程当中,阈值溢出归零,则按阈值公式从新计算 if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; //建立新的hash数组,hash数组的初始化也是在这里完成的 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; //若是旧的hash数组不为空,则遍历旧数组并映射到新的hash数组 if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null;//GC 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 { //rehash————>从新映射到新数组 Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; /*注意这里使用的是:e.hash & oldCap,若为0则索引位置不变,不为0则新索引=原索引+旧数组长度*/ 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; }
上面的代码作了三件事:安全
newCap
和新阈值 newThr
//若链表长度小于该值,则由TreeNode链表转成Node链表 static final int UNTREEIFY_THRESHOLD = 6; /*将红黑树拆分红TreeNode链表后从新映射到新数组*/ final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) { TreeNode<K,V> b = this; TreeNode<K,V> loHead = null, loTail = null; TreeNode<K,V> hiHead = null, hiTail = null; int lc = 0, hc = 0; /*红黑树节点仍然保留了 next 引用,故仍能够按链表方式遍历红黑树*/ /*下面的循环是对红黑树节点进行分组,与上面相似*/ for (TreeNode<K,V> e = b, next; e != null; e = next) { next = (TreeNode<K,V>)e.next; e.next = null; if ((e.hash & bit) == 0) { if ((e.prev = loTail) == null) loHead = e; else loTail.next = e; loTail = e; ++lc; } else { if ((e.prev = hiTail) == null) hiHead = e; else hiTail.next = e; hiTail = e; ++hc; } } if (loHead != null) { //若是 loHead 不为空,且链表长度小于等于 6,则将红黑树转成链表 if (lc <= UNTREEIFY_THRESHOLD) tab[index] = loHead.untreeify(map); else { tab[index] = loHead; // hiHead == null 时,代表扩容后,全部节点仍在原位置,树结构不变,无需从新树化 if (hiHead != null) loHead.treeify(tab); } } // 与上面相似 if (hiHead != null) { if (hc <= UNTREEIFY_THRESHOLD) tab[index + bit] = hiHead.untreeify(map); else { tab[index + bit] = hiHead; if (loHead != null) hiHead.treeify(tab); } } }
在扩容过程当中,树化
要知足两个条件:数据结构
8
)64
)//当链表长度小于该值,不进行树化 static final int TREEIFY_THRESHOLD = 8; //当桶数组容量小于该值时,优先进行扩容,而不是树化 static final int MIN_TREEIFY_CAPACITY = 64; //TreeNode节点(变相继承了Node节点,因此包含next引用) static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } } /*将普通节点链表转换成树形节点链表*/ final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; //桶数组容量小于64,优先进行扩容而不是树化 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { //hd指向树形链表头节点,tl指向尾节点 TreeNode<K,V> hd = null, tl = null; do { //将链表中的Node节点转成TreeNode节点 TreeNode<K,V> p = replacementTreeNode(e, null);//e为当前节点 if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) //将包含TreeNode节点的链表转成红黑树 hd.treeify(tab); } } //Node————>TreeNode TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) { return new TreeNode<>(p.hash, p.key, p.value, next); }
为何桶数组容量大于等于64
才树化?
由于当桶数组容量比较小时,键值对节点 hash 的碰撞率可能会比较高,进而致使链表长度较长。这个时候应该优先扩容,而不是立马树化。ide
HashMap中并非直接经过key的hashcode方法获取哈希值,而是经过内部自定义的hash方法计算哈希值
咱们来看看hash()的实现函数
/** * 计算key的hash值 */ static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
(h = key.hashCode()) ^ (h >>> 16) 是为了让高位数据与低位数据进行异或
,变相的让高位数据参与到计算中,int有32位,右移16位就能让低16位和高16位进行异或来看看get方法优化
/** *获取key映射的value */ public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value;//hash(key)不等于key.hashCode } /*查找key*/ final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; //指向hash数组 Node<K,V> first, e; //first指向hash数组连接的第一个节点,e指向下一个节点 int n;//hash数组长度 K k; /*(n - 1) & hash ————>根据hash值计算出在数组中的索引index(至关于对数组长度取模,这里用位运算进行了优化)*/ if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //基本类型用==比较,其它用euqals比较 if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { //若是first是TreeNode类型,则调用红黑树查找方法 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; }
注意:在HashMap中用 (n - 1) & hash
计算key所对应的索引index(至关于对数组长度取模,这里用位运算进行了优化)this
HashMap插入逻辑:
1.当桶数组 table 为空时,经过扩容的方式初始化 table
2.查找要插入的键值对是否已经存在,存在的话根据条件判断是否用新值替换旧值
3.若是不存在,则将键值对链入链表中,并根据链表长度决定是否将链表转为红黑树
4.判断键值对数量是否大于阈值,大于的话则进行扩容操做
/* * 插入key-value */ 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;//指向hash数组 Node<K,V> p;//初始化为桶中第一个节点 int n, i;//n为数组长度,i为索引 //tab被延迟到插入新数据时再进行初始化 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //若是桶中不包含Node引用,则新建Node节点存入桶中便可 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null);//new Node<>(hash, key, value, next) else { Node<K,V> e; //若是要插入的key-value已存在,用e指向该节点 K k; //若是第一个节点就是要插入的key-value,则让e指向第一个节点(p在这里指向第一个节点) if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //若是p是TreeNode类型,则调用红黑树的插入操做(注意:TreeNode是Node的子类) else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //对链表进行遍历,并用binCount统计链表长度 for (int binCount = 0; ; ++binCount) { //若是链表中不包含要插入的key-value,则将其插入到链表尾部 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //若是链表长度大于或等于树化阈值,则进行树化操做 if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); break; } //若是要插入的key-value已存在则终止遍历,不然向后遍历 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } //若是e不为null说明要插入的key-value已存在 if (e != null) { V oldValue = e.value; //根据传入的onlyIfAbsent判断是否要更新旧值 if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e);//空函数?回调?不知道干吗的 return oldValue; } } ++modCount; //键值对数量超过阈值时,则进行扩容 if (++size > threshold) resize(); afterNodeInsertion(evict);//也是空函数?回调?不知道干吗的 return null; }
HashMap 的删除操做并不复杂,仅需三个步骤便可完成。第一步是定位桶位置,第二步遍历链表并找到键值相等的节点,第三步删除节点,源码以下:
/* * 删除元素 */ 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; // 若是键的值与链表第一个节点相等,则将 node 指向该节点 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) { // 若是是 TreeNode 类型,调用红黑树的查找逻辑定位待删除节点 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; }
注意:删除节点后可能破坏了红黑树的平衡性质,removeTreeNode方法会对红黑树进行变色、旋转等操做来保持红黑树的平衡结构,这部分比较复杂,感兴趣的小伙伴可看下面这篇文章:
红黑树详解
最多见的遍历方式
for(Object key : map.keySet()) { // do something }
等价于
Set keys = map.keySet(); Iterator ite = keys.iterator(); while (ite.hasNext()) { Object key = ite.next(); // do something }
在遍历HashMap时,咱们会发现遍历的顺序和插入的顺序不一致,这是为何呢?
咱们这里以keySet
为例,先来看看部分相关源码:
public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; } /** * 键集合 */ final class KeySet extends AbstractSet<K> { public final Iterator<K> iterator() { return new KeyIterator(); } // 省略部分代码 } /** * 键迭代器 */ final class KeyIterator extends HashIterator implements Iterator<K> { public final K next() { return nextNode().key; } } /*HashMap迭代器基类,子类有KeyIterator、ValueIterator等*/ abstract class HashIterator { Node<K,V> next; //下一个节点 Node<K,V> current; //当前节点 int expectedModCount; //修改次数 int index; //当前索引 //无参构造 HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; //找到第一个不为空的桶的索引 if (t != null && size > 0) { do {} while (index < t.length && (next = t[index++]) == null); } } //是否有下一个节点 public final boolean hasNext() { return next != null; } //返回下一个节点 final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException();//fail-fast if (e == null) throw new NoSuchElementException(); //当前的桶遍历完了就开始遍历下一个桶 if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; } //删除元素 public final void remove() { Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; K key = p.key; removeNode(hash(key), key, null, false, false);//调用外部的removeNode expectedModCount = modCount; } }
从代码能够看出,HashIterator
先从桶数组中找到包含链表节点引用的桶。而后对这个桶指向的链表进行遍历。遍历完成后,再继续寻找下一个包含链表节点引用的桶,找到继续遍历。找不到,则结束遍历。这就解释了为何遍历和插入的顺序不一致,不懂的同窗请看下图:
本文描述了HashMap的实现原理,并结合源码作了进一步的分析,也涉及到一些源码细节设计原因,但愿本篇文章能帮助到你们,同时也欢迎讨论指正,谢谢支持!
关于HashMap的源码就讲解到这里了,如今咱们来讲说为何添加到HashMap中的对象须要重写equals()
和hashcode()
方法?
这里以Person为例:
public class Person { Integer id; String name; public Person(Integer id, String name) { this.id = id; this.name = name; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj instanceof Person) { Person person = (Person) obj; if (this.id == person.id) return true; } return false; } public static void main(String[] args) { Person p1 = new Person(1, "aaa"); Person p2 = new Person(1, "bbb"); HashMap<Person, String> map = new HashMap<>(); map.put(p1, "这是p1"); System.out.println(map.get(p2)); } }
Person类重写equals方法来根据id判断是否相等,当没有重写hashcode方法时,插入p1后便没法用p2取出元素,
这是由于p1和p2的哈希值不相等。
HashMap插入元素时是根据元素的哈希值来肯定存放在数组中的位置
,所以HashMap的key
须要重写equals和hashcode方法。