美文网首页JavaWebJava 杂谈
HashMap底层详解-001-数据结构、put、get

HashMap底层详解-001-数据结构、put、get

作者: 53b3f4658edc | 来源:发表于2017-11-14 20:41 被阅读67次

    今天小粉粉去某公司参加Java开发工程师的面试了。但是不太顺利,然后她遇见了小灰灰……

    微信公众号:JavaWeb架构师 微信公众号:JavaWeb架构师
    1. HashMap的数据结构
    • HashMap的数据结构是 数组+链表 的形式组成的。
    微信公众号:JavaWeb架构师
    • 数组(这个table就是咱们看见的数组部分。)
        /**
         * The table, initialized on first use, and resized as
         * necessary. When allocated, length is always a power of two.
         * (We also tolerate length zero in some operations to allow
         * bootstrapping mechanics that are currently not needed.)
         */
    
         /**
          * 在第一次使用时初始化的表,并调整为
          * 必要的。当分配时,长度总是2的幂。
          * (在某些操作中,我们还可以容忍长度为0
          * 目前不需要的引导机制。)
          */
        transient Node<K,V>[] table;
    
    • 链表(在数组元素的内部)
    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    /**
     * 基本的哈希本节点,用于大多数条目。(见下文
     * TreeNode子类,在LinkedHashMap中用于它的入口子类。)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        // 指向下一个元素的引用(形成内部的链表)
        Node<K,V> next;
    
       // …………
    }
    
    1. put、get
    • put:
      • 先根据put进来的元素的key值对应的hash值得到这个元素应该存放在table中的位置(index)

      • 把这个元素放入到index位置上。如果这个index上已经存放有其他元素了,那在同一个位子上的元素将以链表的形式存放,新加入的放在链头(头插法)

    
        /**
         * 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;
            // 第一次使用table,初始化长度
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
    
            // 应该存放的位置的值是 null,那就直接把元素put到这个位置
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            // 这个位置已经有元素存在了
            else {
                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 {
                    // 头插
                    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) { // 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;
        }
    
    • get:
      • 先根据get元素的key值对应的hash值得到这个元素应该存放在table中的位置(index)

      • 再在这个index的元素的链表中去equals(key),如果相等的话,那就是要get的值(顺便一提:实现者认为后面插入的被查找的概率更大,所以使用了头插法)

    微信公众号:JavaWeb架构师 微信公众号:JavaWeb架构师 微信公众号:JavaWeb架构师


    欢迎加入交流群:451826376


    更多信息:www.itcourse.top

    完整教程PDF版本下载

    相关文章

      网友评论

        本文标题:HashMap底层详解-001-数据结构、put、get

        本文链接:https://www.haomeiwen.com/subject/jgvfvxtx.html