zoukankan      html  css  js  c++  java
  • Java源码-HashMap(jdk1.8)

    一、hash方法

    如下是jdk1.8中的源码

    1 static final int hash(Object key) {
    2         int h;
    3         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    4 }

    (1)HashMap允许一个key为空,因此key为null 的hash 值为0。

           a、首先获取对象的hashCode()值;

           b、然后将hashCode值右移16位;

           c、然后将右移后的值与原来的hashCode做异或运算,返回结果。

         (其中h>>>16,在JDK1.8中,优化了高位运算的算法,使用了零扩展,无论正数还是负数,都在高位插入0)。

    (2)在putVal源码中,我们通过(n-1)&hash获取该对象的键在hashmap中的位置

            (其中hash的值就是(1)中获得的值)

           其中n表示的是hash桶数组的长度,并且该长度为2的n次方,这样(n-1)&hash就等价于hash%n。

           因为&运算的效率高于%运算。

    1 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
    2                    boolean evict) {
    3         ...
    4
    5         if ((p = tab[i = (n - 1) & hash]) == null)//获取位置
    6             tab[i] = newNode(hash, key, value, null);
    7         ...
    8 }

     二、putVal方法

    jdk1.8中hashmap 的实现是通过数组+链表+红黑树来实现的,如果链表的结点数大于8,那么就将链表重构成红黑树。

     完善了一张前利作者的图:

      1 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
      2                    boolean evict) {
      3         Node<K,V>[] tab; Node<K,V> p; int n, i;
      4         if ((tab = table) == null || (n = tab.length) == 0)
      5             n = (tab = resize()).length;//如果当前hashMap中无数据,那么调用resize()方法扩容
      6         if ((p = tab[i = (n - 1) & hash]) == null)//如果当前通过hash方法找到的hash桶数组中没有值
      7             tab[i] = newNode(hash, key, value, null);//那么直接在当前结点新建结点对象
      8         else {//如果在当前hash桶数组中该位置有值了
      9             Node<K,V> e; K k;//比较该位置的hash值与传入的参数hash值是否相等,并且key值是否相等
     10             if (p.hash == hash && //即判断是否是同一个key对象
     11                 ((k = p.key) == key || (key != null && key.equals(k))))
     12                 e = p;//如果是,那么将当前数组中的对象p 赋值给 临时对象e,然后在下面替换掉value值就可以了,执行第29行。
     13             else if (p instanceof TreeNode)//如果不是同一key对象,那么判断p是否是红黑树结点
     14                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//如果是,那么在红黑树中插入结点
     15             else {//如果不是,那么就是普通的结点了,即存放在链表中
     16                 for (int binCount = 0; ; ++binCount) {
     17                     if ((e = p.next) == null) {//找到链表的最后一个结点
     18                         p.next = newNode(hash, key, value, null);//插入新节点
     19                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
     20                             treeifyBin(tab, hash);//如果大于8,那么重构成红黑树
     21                         break;
     22                     }
     23                     if (e.hash == hash &&
     24                         ((k = e.key) == key || (key != null && key.equals(k))))
     25                         break;//如果在链表中存在的是同一个key对象,那么直接在下面的方法中替换掉
     26                     p = e;
     27                 }
     28             }//如果当前位置的对象是同一对象,那么直接替换掉
     29             if (e != null) { // existing mapping for key
     30                 V oldValue = e.value;
     31                 if (!onlyIfAbsent || oldValue == null)
     32                     e.value = value;
     33                 afterNodeAccess(e);
     34                 return oldValue;
     35             }
     36         }
     37         ++modCount;
     38         if (++size > threshold)//如果超过当前的阀值,那么扩容
     39             resize();
     40         afterNodeInsertion(evict);
     41         return null;
     42     }

    三、resize方法

    (1) 在jdk1.8中,resize方法是在hashmap中的键值对大于阀值时或者初始化时,就调用resize方法进行扩容;

    (2)每次扩展的时候,都是扩展2倍;

    (3)扩展后Node对象的位置要么在原位置,要么移动到原偏移量两倍的位置。

     1  final Node<K,V>[] resize() {
     2         Node<K,V>[] oldTab = table;//oldTab指向hash桶数组
     3         int oldCap = (oldTab == null) ? 0 : oldTab.length;
     4         int oldThr = threshold;
     5         int newCap, newThr = 0;
     6         if (oldCap > 0) {//如果oldCap不为空的话,就是hash桶数组不为空
     7             if (oldCap >= MAXIMUM_CAPACITY) {//如果大于最大容量了,就赋值为整数最大的阀值
     8                 threshold = Integer.MAX_VALUE;
     9                 return oldTab;//返回
    10             }//如果当前hash桶数组的长度在扩容后仍然小于最大容量 并且oldCap大于默认值16
    11             else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
    12                      oldCap >= DEFAULT_INITIAL_CAPACITY)
    13                 newThr = oldThr << 1; // double threshold 双倍扩容阀值threshold
    14         }
    15         else if (oldThr > 0) // initial capacity was placed in threshold
    16             newCap = oldThr;
    17         else {               // zero initial threshold signifies using defaults
    18             newCap = DEFAULT_INITIAL_CAPACITY;
    19             newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    20         }
    21         if (newThr == 0) {
    22             float ft = (float)newCap * loadFactor;
    23             newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
    24                       (int)ft : Integer.MAX_VALUE);
    25         }
    26         threshold = newThr;
    27         @SuppressWarnings({"rawtypes","unchecked"})
    28             Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//新建hash桶数组
    29         table = newTab;//将新数组的值复制给旧的hash桶数组
    30         if (oldTab != null) {//进行扩容操作,复制Node对象值到新的hash桶数组
    31             for (int j = 0; j < oldCap; ++j) {
    32                 Node<K,V> e;
    33                 if ((e = oldTab[j]) != null) {//如果旧的hash桶数组在j结点处不为空,复制给e
    34                     oldTab[j] = null;//将旧的hash桶数组在j结点处设置为空,方便gc
    35                     if (e.next == null)//如果e后面没有Node结点
    36                         newTab[e.hash & (newCap - 1)] = e;//直接对e的hash值对新的数组长度求模获得存储位置
    37                     else if (e instanceof TreeNode)//如果e是红黑树的类型,那么添加到红黑树中
    38                         ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
    39                     else { // preserve order
    40                         Node<K,V> loHead = null, loTail = null;
    41                         Node<K,V> hiHead = null, hiTail = null;
    42                         Node<K,V> next;
    43                         do {
    44                             next = e.next;//将Node结点的next赋值给next
    45                             if ((e.hash & oldCap) == 0) {//如果结点e的hash值与原hash桶数组的长度作与运算为0
    46                                 if (loTail == null)//如果loTail为null
    47                                     loHead = e;//将e结点赋值给loHead
    48                                 else
    49                                     loTail.next = e;//否则将e赋值给loTail.next
    50                                 loTail = e;//然后将e复制给loTail
    51                             }
    52                             else {//如果结点e的hash值与原hash桶数组的长度作与运算不为0
    53                                 if (hiTail == null)//如果hiTail为null
    54                                     hiHead = e;//将e赋值给hiHead
    55                                 else
    56                                     hiTail.next = e;//如果hiTail不为空,将e复制给hiTail.next
    57                                 hiTail = e;//将e复制个hiTail
    58                             }
    59                         } while ((e = next) != null);//直到e为空
    60                         if (loTail != null) {//如果loTail不为空
    61                             loTail.next = null;//将loTail.next设置为空
    62                             newTab[j] = loHead;//将loHead赋值给新的hash桶数组[j]处
    63                         }
    64                         if (hiTail != null) {//如果hiTail不为空
    65                             hiTail.next = null;//将hiTail.next赋值为空
    66                             newTab[j + oldCap] = hiHead;//将hiHead赋值给新的hash桶数组[j+旧hash桶数组长度]
    67                         }
    68                     }
    69                 }
    70             }
    71         }
    72         return newTab;
    73     }

    四、get方法

    (1)get(Object key)

     一般我们是通过get(key)来获取对象的键值,在jdk1.8源码中,通过getNode(hash(key),key)来获取结点对象,如果返回的结果不为空,那么就表示有对应的结点,返回e.value。

    1 public V get(Object key) {
    2         Node<K,V> e;
    3         return (e = getNode(hash(key), key)) == null ? null : e.value;
    4     }

    (2)getNode(int hash, Object key)

     1 final Node<K,V> getNode(int hash, Object key) {
     2         Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
     3         if ((tab = table) != null && (n = tab.length) > 0 &&
     4             (first = tab[(n - 1) & hash]) != null) {
     5             if (first.hash == hash && // 总是从第一个检查开始 ,比较hash值 和key值
     6                 ((k = first.key) == key || (key != null && key.equals(k))))
     7                 return first;
     8             if ((e = first.next) != null) {
     9                 if (first instanceof TreeNode)//如果是红黑树类型,那么在红黑树中查找
    10                     return ((TreeNode<K,V>)first).getTreeNode(hash, key);
    11                 do {
    12                     if (e.hash == hash &&
    13                         ((k = e.key) == key || (key != null && key.equals(k))))
    14                         return e;
    15                 } while ((e = e.next) != null);//循环遍历
    16             }
    17         }
    18         return null;//表示没有找到
    19     }

    (3)啦啦啦

  • 相关阅读:
    Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function问题解决
    Fiddler是最强大最好用的Web调试工具之一--网站抓包分析
    django 运行不同的settings
    Ununtu 15.04 安装MySql(Django连接Mysql)
    Linux SSH登录服务器报ECDSA host key "ip地址" for has changed and you have requested strict checking.错误
    解决将Ubuntu下导出的requirements.txt到Centos服务器上面出现pkg-resource的版本为0.0.0
    Ubuntu安装Nginx和正确卸载Nginx Nginx相关
    jquery 情况form表单的所有内容
    python把中文文档变为拼音
    将多个文件夹内的txt合并
  • 原文地址:https://www.cnblogs.com/fankongkong/p/6731896.html
Copyright © 2011-2022 走看看