HashMap源码分析
Posted jiaqirumeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap源码分析相关的知识,希望对你有一定的参考价值。
在java中,hashmap是一种非常重要的数据结构,现在我们来分析一下它的实现逻辑。
我们知道hashmap是存储键值对的结构,它的存储和查询都很快,而基于数组的ArrayList有较快的查询速度,和基于链表的LinendList有很好的易修改性能
hashmap则是结合了这两者的优点,大概长这样
HashMap的成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//16 数组初始大小 static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量 static 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;//数据实际存储位置,node数组 transient Set<Map.Entry<K,V>> entrySet;// transient int size;//键值对数量 transient int modCount;//修改次数 int threshold;//阈值--数组扩容相关 final float loadFactor;//加载因子
HashMap构造函数
public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0)//初始容量不能小于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); }
HashMap的存储单元
包含一个hash值,Key Value 和下一个节点引用
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key;//确保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 添加键值对
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
//1.计算hash值 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } 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))))//判断hash值和key是否和这个对象的一样,如果一样说明key是一样,替换原有键值对 e = p; else if (p instanceof TreeNode)//如果不一样(hash冲突),判断是否是树型节点 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//插入树型节点 else {//hash冲突,非树型节点,往链表后插入数据 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))))//hash相同 键相同 跳出循环处理 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 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; } 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); } }
有几个值得注意的点:
1.hash值计算
h = key.hashCode()) ^ (h >>> 16
这是将int类型的值右移16位,得到的h 和int的所有位数相关,保证了散列性(降低hash冲突可能性)。
2.数组下标计算
i = (n - 1) & hash
这里使用 & 保证下标不会超出 n - 1,& hash 保证了下标的散列性
以上是关于HashMap源码分析的主要内容,如果未能解决你的问题,请参考以下文章