HashMap源码注释

核心理论

Hash也称散列、哈希,基本原理就是把任意长度的的输入,通过Hash算法变成固定长度的输出
这个映射的规则就是对应的Hash算法,而原始数据映射后的二进制串就是哈希值

Hash的特点:

1、从hash值不可以反向推导出原始的数据
2、输入的微小变化会得到完全不同的hash值,相同的数据会得到相同的值
3、哈希算法的执行效率要高效长的文本也能快速的计算出哈希值
4、hash算法的冲突概率要小
由于hash的原理是将输入空间的值映射成hash空间内。而hash值的空间要小于输入的空间
根据抽屉原理,一定会存在不同的输入被映射成相同输出的情况

Hamp的外层是一个Node数组 默认长度16 数字里存放的是哈希值 如果hash发生冲突之后会形成链表 链表长度大于8时 (注意:当哈希表中所有元素的个数超过64时,才会允许树化)链表结构将升级为红黑树

为什么引入红黑数:

当存数据时 hash 发生冲突之后会形成链表 如果冲突的次数比较多那么链表的长度会很长 这样查询的效率机会很而将链表结构升级为红黑树 因为是二叉树结构 所以查询的效率会提高

put方法:

  static final int hash(Object key) {
    //如果key为null 那直接返回0 不为null key的hash值进行扰动(异或算法 并右移16为 作用:让高16位也参与运算)
    int h;//异或:相同返回0 不同返回1
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  }


  // put时先计算key的Hash值
    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) {
     // tab:引用当前HashMap的散列表  p:表示当前散列标的元素  n:表示散列表的数组长度 i:表示路由地址:结果
        Node<K,V>[] tab; Node<K,V> p; int n, i;
     //延迟初始化逻辑,第一次调用putVal时会初始化HashMap中最耗内存的散列表  这样做的原因是避免创建了对象但是没有使用 而散列表又是比较耗费内存的 所有只有第一次使用的时候再去初始化  
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
     //最简单的一种情况:寻址找到桶位,刚好是null 这个时候 直接将当前的k-v封装成Node对象 扔进去就可以了 注意:这里是用寻址算法找到要存放的位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
        // e:e不为null的话,找到了与一个与当前要插入的key-valye完全一致的元素
        //k:临时的key
            Node<K,V> e; K k;
       //表示如果桶位中的元素与当前要插入的key完全一致 后续要进行替换操作
            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 {
          //链表的情况 链表的头元素与要插入的key不一致 
                for (int binCount = 0; ; ++binCount) {
            //如果条件成立的话,说明到了最后一个元素,也没有找到要插入的key一致的Node ,那就说明需要添加到链表的末尾
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
              //如果链表的长度大于8 进行树化操作  (TREEIFY_THRESHOLD的值是8 )
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                           //树化操作 
                treeifyBin(tab, hash);
                        break;
                    }
            //如果条件相同 说明找到了key相同的Node ,需要进行替换 
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
       //e不等于null 说明找到了与插入元素key完全一致的数据 进行替换
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
    //modCount:表示散列表结构被修改的次数,替换Node元素的value不计数
    //插入一个新元素加1
        ++modCount;
     //size:散列表中Node的数量  如果Node的数量大于阈值 进行扩容 插入新元素size加1
        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);
        }
    }


   
   final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

//扩容方法
 final Node<K,V>[] resize() {
    //oldTab:引用扩容前的哈希表
        Node<K,V>[] oldTab = table;
     //扩容前的数组长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
     //扩容前的扩容阈值 触发本次的扩容阈值
        int oldThr = threshold;
     //newCap:扩容后的哈希表大小,newThr:下次触发扩容机制的阈值
        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);
        }
     //newThr为0时通过newCap和loadFactor计算出一个newThr
        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;
     // 说明本次扩容之前 hashMap不为null (存在数据 上面有写 new一个HashMap 但并未使用的时候哈希表是没有初始化的)
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
          //当前Node节点
                Node<K,V> e;
          // 说明当前桶位中有数据 但是是单个数据 还是链表或者红黑树是不确定
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;// 原始数据赋值为null 方便jvm回收
                    // 第一种情况:如果当前节点的下一个节点为空 就说明当前桶位既不是链表也不是红黑树 因为它没下一个 就不可能是链表 更不可能是红黑树
            //这种情况,直接计算出当前元素在数组中的位置 直接存到新数组中就ok了 算法:hash &(lenght-1) = index (hash值&(数组长度-1)=数组的index)
            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;
    }

 

 

get方法:

// 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) {
        // tab:引用当前HashMap的散列表
        //first:桶位中的头元素
        //e:临时Node元素
        // n:Table数组长度
        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) {
         //第一种情况:桶位中的头元素,就是要get的数据   
        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;
    }                                            

 

posted @ 2021-06-03 18:00  luxuewu  阅读(78)  评论(0)    收藏  举报