jdk1.7之前Hashmap使用数组加链表实现。
jdk1.8之后引入了红黑树。红黑树,左子树比结点小,右子树比结点大,提高了查询的效率。
Hashmap的put操作(JDK1.8)
1.计算添加对象的hashCode值(类中应该重写hashCode值和equals方法),若hashCode经过一定的算法计算与原数组已经有了的对象冲突,需要比较hashCode值,若hashCode值不同,原有对象以链表形式指向后添加的对象,添加成功。
2.若hashCode值相同,再调用equals方法,比较是否相同,若不相同,同样以链表形式添加其后。
3.若调用equals方法相同,则put方法的实际作用是将相同对象的原value值改为新对象的value值,即修改作用。
4.当使用put操作,当链表长度达到>=7时,判断数组长度是否大于64,若不大于就扩容,大于就变红黑树。
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); //TREEIFY_THRESHOLD为8 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; }
红黑树方法块
final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } }
HashMap底层实现原理
于 2022-04-19 19:19:41 首次发布