HashMap源码解析——put方法
来源:互联网 发布:windows 7 下载 iso 编辑:程序博客网 时间:2024/06/05 00:17
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
先看hash(key)函数。它是通过key的hashCode值计算hash码。
//计算hash值的方法 通过键的hashCode来计算static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
得到hash码之后就会通过hash码去计算出应该存储在数组中的索引,计算索引的函数如下:
static int indexFor(int h, int length) { //根据hash值和数组长度算出索引值 return h & (length-1); //这里不能随便算取,用hash&(length-1)是有原因的,这样可以确保算出来的索引是在数组大小范围内,不会超出 }
这个我们要重点说下,我们一般对哈希表的散列很自然地会想到用hash值对length取模(即除法散列法),Hashtable中也是这样实现的,这种方法基本能保证元素在哈希表中散列的比较均匀,但取模会用到除法运算,效率很低,HashMap中则通过h&(length-1)的方法来代替取模,同样实现了均匀的散列,但效率要高很多,这也是HashMap对Hashtable的一个改进。
接下来,我们分析下为什么哈希表的容量一定要是2的整数次幂。首先,length为2的整数次幂的话,h&(length-1)就相当于对length取模,这样便保证了散列的均匀,同时也提升了效率;其次,length为2的整数次幂的话,为偶数,这样length-1为奇数,奇数的最后一位是1,这样便保证了h&(length-1)的最后一位可能为0,也可能为1(这取决于h的值),即与后的结果可能为偶数,也可能为奇数,这样便可以保证散列的均匀性,而如果length为奇数的话,很明显length-1为偶数,它的最后一位是0,这样h&(length-1)的最后一位肯定为0,即只能为偶数,这样任何hash值都只会被散列到数组的偶数下标位置上,这便浪费了近一半的空间,因此,length取2的整数次幂,是为了使不同hash值发生碰撞的概率较小,这样就能使元素在哈希表中均匀地散列。
下面我们来看putVal方法
//putVal被final修饰,不能被重写。(起初博主在此处有些许疑问,此处为什么要用putVal方法,而不是重载put方法。后来一看final修饰,估计用意是为了和put方法区分开,实际是在putVal方法中实现存储数据,当外部重写了put方法时(如有必要),也不影响HashMap存储数据。)
/** * Implements Map.put and related methods * * @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) { 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 { // 循环遍历Node数组,若“该key”对应的键值对已经存在,则用新值替换旧值。然后退出! 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) { //如果key相同则覆盖并返回旧值 V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } //修改次数+1 ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
调整HashMap大小
resize()方法如下:
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; }
方法很长,着重看前面这两句
newCap = oldCap << 1
newThr = oldThr << 1;
就是数组长度扩容为原来的二倍,数组长度变了,自然临界值也要变为原来的二倍。
- HashMap源码解析——put方法
- HashMap之put方法源码解析
- java 8 Hashmap深入解析 —— put get 方法源码
- java 8 Hashmap深入解析 —— put get 方法源码
- java 8 Hashmap深入解析 —— put get 方法源码
- java 8 Hashmap深入解析 —— put get 方法源码
- HashMap的put源码解析
- HashMap源码解析——构造方法
- HashMap源码解析——get方法
- HashMap源码--(三)put方法
- HashMap中的数据结构与get,put源码解析
- HashMap的put()方法
- HashMap.put/get方法
- HashMap源码注解 之 put()方法(六)
- Java 1.8 HashMap 源码中 put()方法详解
- 【源码分析】HashMap的put(K k,V v)方法
- HashMap学习笔记:put方法
- HashMap源码解析——概述
- Linux 网卡驱动学习(一)(分析一个虚拟硬件的网络驱动例子)
- orcal 忘记用户名和密码
- c++中“箭头(->)”和“点号(.)”操作符的区别 .
- Java 时间日期API总结
- 将10进制的字符串转为16进制的byte
- HashMap源码解析——put方法
- python基础(2)
- 第八届福建省大学生程序设计竞赛-重现赛(F Problem 2277 Change)DFS序+树状数组
- java基础之String类总结
- What Is Your Grade? (sort)
- 华为机试题-合唱队
- java concurrent-Callable FutureTask
- 进制之间的转换
- 个人总结 2017.7.23