jdk1.8 HashMap源码分析
2017-11-07 10:13
281 查看
jdk1.8 HashMap源码分析
jdk1.8中对于HashMap的源码进行了一些改动,本文先对hashmap中常用的方法源码进行分析,看看究竟发生了什么put方法
public V put(K key, V value) { //真正执行是在putVal方法中 return putVal(hash(key), key, value, false, true); } /** * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { //新建几个指针,tab指向当前数组,p指向当先下标上的头结点,n表示当前数组长度,i表示当前数组下标 Node<K,V>[] tab; Node<K,V> p; int n, i; //如果table还未初始化,先进行初始化 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //如果新节点所在数组下标位置上还没有节点,直接新建一个 if ((p = tab[i = (n - 1) & hash]) == null) //这里(n - 1) & hash是计算新节点的数组下标 tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //如果新节点和当前节点hash值完全一样并且key值相等,则直接替换,这也就是为什么重写equals方法时必须同时重写hashCode if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //如果当前节点是TreeNode类型,则按照红黑树的方式添加节点。较1.7区别1 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //遍历当前节点上的链表 for (int binCount = 0; ; ++binCount) { //已经遍历到链表的尾部,新增一个节点,停止,e为空。较1.7区别2 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //当达到阈值,将链表转换为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //遍历过程中,如果发现完全相同的节点,停止,e指向该节点 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } //如果e不是空,则将e的值替换为新值 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue b49d == null) e.value = value; afterNodeAccess(e); return oldValue; } } //迭代器使用,迭代器初始化时会记录,如果迭代过程中该值有变化,则抛出异常 ++modCount; //超过阈值,扩容 if (++size > threshold) resize(); //linkedHashMap中会用到,如果evict为true,会把链表头踢出去 afterNodeInsertion(evict); return null; } /** * 这一部分代码比较重要,table的初始化和扩容都在该方法中完成 */ 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) { //如果旧的长度超过了最大长度(1<<30),阈值大小设为int类型最大 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; //e.hash & oldCap为0,则数组下标不变,这里涉及很巧妙,没有理解的同学可以自己动手算一下 if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } e.hash & oldCap不为0,需要移动 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; } /** * hash算法,该方法在寻址是使用,目的在于让Int类型的数高16位也参与运算,提高散列度 */ static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
get方法
附上源码,代码写的很清楚,就是寻址+遍历public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { 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; }
知识点
jdk1.8中hashmap的结构为数组+链表+红黑树
hashMap链表初始长度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
寻址方法
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } tab[i = (n - 1) & hash]
先将key的高16位和低16位做异或,然后和数组长度n-1做位与,由于数组长度为2^x,所以(n - 1) & hash可以计算出数组的下标
重写equals()方法时对象时必须重写hashCode()方法
因为hashMap中判定两个key相同的代码为:
p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))
链表长度超过8,则将链表树化
static final int TREEIFY_THRESHOLD = 8;
原因:红黑树的查询复杂度为O(logn),链表查询复杂度为O(n),当n=8时,红黑树平均查找长度为3,链表为4,红黑树查找的速度会高于链表
java1.7之前,新增节点会新增至链表的头结点,是为了防止每次新增节点都要遍历至链表尾部,1.8中引入了红黑树,不存在该问题,所以新增节点会增至链表尾节点
相关文章推荐
- JDK1.8 HashMap 源码分析
- JDK1.8的HashMap源码分析
- jdk1.8中HashMap源码分析流程图
- JDK1.8 HashMap中put源码分析
- JDK1.8 HashMap中put源码分析
- JDK1.8源码分析之HashMap(一) (转)
- jdk1.8 HashMap源码分析(构造函数)
- jdk1.8 HashMap源码分析(resize函数)
- HashMap源码分析 JDK1.8
- Hashmap和hashtable三大区别(从源码角度分析为什么map可以存放一个key为null,多个值为null)的特点
- 【JDK源码分析】浅谈HashMap的原理
- HashMap与HashTable的区别(源码分析),不喜欢背概念
- HashMap源码分析
- HashMap实现原理及源码分析
- Java Collections Framework之HashMap源码分析(基于JDK1.6)
- JDK1.7 中的HashMap源码分析
- HashMap源码分析(基于JDK1.6)
- HashMap源码分析
- HashMap EntrySet源码 分析(修改版)
- HashMap 源码分析