HashMap源码阅读

背景: 昨天面试udesk, 技术主管问HashMap / ConcurrentHashMap / ThreadLocalPool 源码的细节,全程懵逼,反思了一下,之前的工作都是在写业务代码,没有深入细节,故作此篇。
心态:慌得一批
版本:jdk 1.8.0_161
工具:IntelliJ IDEA 2018.1
难点:成体系的解读好难....目前只做散乱的记录,哪哪都难
储备知识:业务代码
体验:也不是特别难...map长度的初始化,第一次存放数据的时候

  1. Class的继承关系
HashMap extends AbstractMap implements Map, Cloneable, Serializable
image.png
  1. 内部核心类::存储数据的实体,包装了key-value键值对
    1. HashMap.Node
    /**
     * Basic hash bin node, used for most entries. 
     * (See below for
     * TreeNode subclass, 
     * and in LinkedHashMap for its Entry subclass.)
     */
    static class Node implements Map.Entry {
        final int hash;
        final K key;
        V value;
        Node next;
    
        public final int hashCode() {
           ...
        }
    
        public final V setValue(V newValue) {
            ...
        }
    
        public final boolean equals(Object o) {
            ...
        }
    }
    
    1. LinkedHashMap.Entry 继承关系
    /**
    * HashMap.Node subclass for normal LinkedHashMap entries.
    */
    static class Entry extends HashMap.Node {
       Entry before, after;
       Entry(int hash, K key, V value, Node next) {
           super(hash, key, value, next);
       }
    }
    

  1. put(K key,V value)
/**
   * Associates the specified value with the specified key in this map.
   * If the map previously contained a mapping for the key, the old
   * value is replaced.
   * 翻译: 在当前的map中关联 value 和 key,
   * 如果 map 中 key 已经有映射关系,那么原有的 value 会被覆盖
   * @param key key with which the specified value is to be associated
   * @param value value to be associated with the specified key
   * @return the previous value associated with key, or
   *         null if there was no mapping for key.
   *         (A null return can also indicate that the map
   *         previously associated null with key.)
   * @return 翻译:如果当前key有关联的value,返回覆盖前的value;如果put之前没值,返回null。
   *  返回一个null,也可能意味着 put 之前 value 的值为 null
   */
  public V put(K key, V value) {
      return putVal(hash(key), key, value, false, true);
  }
  1. putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
  /**
   * 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){
        // Map 里面存放数据的 —— 数据 + 链表
        // 0. Node[] tab;
        // 1. Node  
        Node[] tab; Node p; int n, i;
         // 首次添加元素,调用resize()方法初始化table
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 与运算,判断存储位置的,桶是不是存在,获取桶的首节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 存储数据的格式  Node 
            tab[i] = newNode(hash, key, value, null);
        else {
            // 遍历元素,添加数据
            Node e; K k;
            // 如果 hash 想等,或者 equals 那么替换
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p; //更新p指向下一个节点
            // 如果p类型为TreeNode,调用树的添加元素方法(红黑树冲突插入)
            else if (p instanceof TreeNode)
                e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
            // 不是TreeNode,即为链表,遍历链表,查找给定关键字 
            else {
                for (int binCount = 0; ; ++binCount) {
                    // 到达链表的尾端也没有找到key值相同的节点,则生成一个新的Node
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                       // 创建新节点后若超出树形化阈值,则转换为树形存储
                      // 当桶中链表的数量>=8的时候,底层则改为红黑树实现
                        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;
                }
            }
            // e不为空,即map中存在要添加的关键字  
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
       // 记录hashmap 添加删除元素的 次数
        ++modCount; 
       // size  : key-value 的数目
       // threshold :下一次resize的阈值  (capacity * load factor).
        if (++size > threshold) 
            resize();
       // Callbacks to allow LinkedHashMap post-actions
       // 回调移除最早放入Map的对象,可以用于实现 LRU 算法
       // 默认不会删除,除非重写 LinkedHashMap # removeEldestEntry
        afterNodeInsertion(evict);
        return null;
}

p.next = newNode(hash, key, value, null);

    // Create a regular (non-tree) node
    Node newNode(int hash, K key, V value, Node next) {
        return new Node<>(hash, key, value, next);
    }

三个空函数
HashMap # afterNodeInsertion

    // Callbacks to allow LinkedHashMap post-actions
    void afterNodeAccess(Node p) { }
    void afterNodeInsertion(boolean evict) { }
    void afterNodeRemoval(Node p) { }

LinkedHashMap 具体的实现
LinkedHashMap # afterNodeInsertion

    void afterNodeInsertion(boolean evict) { // possibly remove eldest
        LinkedHashMap.Entry first;
        if (evict && (first = head) != null && removeEldestEntry(first)) {
            K key = first.key;
            removeNode(hash(key), key, null, false, true);
        }
    }
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return false;
    }

    public V remove(Object key) {
        Node e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?null : e.value;
    }
    ... 
    final Node removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node[] tab; Node p; int n, index;
        // 匹配 目标元素 Node node
        //  定位 tab[] 数组下标 
        if ((tab = table) != null && (n = tab.length) > 0 && 
            (p = tab[index = (n - 1) & hash]) != null) {
            Node node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                // 如果是 红黑树...再说吧
                if (p instanceof TreeNode)
                    node = ((TreeNode)p).getTreeNode(hash, key);
                // 只能是 链表,遍历即可
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            // 做元素的删除, 区分 链表  tree 和 首元素 
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

  /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node getNode(int hash, Object key) {
        Node[] tab; Node 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)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;
    }

HashMap 中使用的红黑树 :

  1. 继承关系


    image.png
  2. source code
static final class TreeNode extends LinkedHashMap.Entry {
        TreeNode parent;  // red-black tree links
        TreeNode left;
        TreeNode right;
        TreeNode prev;    // needed to unlink next upon deletion
        boolean red;

        public V get(Object key) {
            Node e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
        /**
         * Tree version of putVal.
         */
        final TreeNode putTreeVal(HashMap map, Node[] tab,
                                       int h, K k, V v) {
              ... 
        }
        /**
         * Removes the given node, that must be present before this call.
         * This is messier than typical red-black deletion code because we
         * cannot swap the contents of an interior node with a leaf
         * successor that is pinned by "next" pointers that are accessible
         * independently during traversal. So instead we swap the tree
         * linkages. If the current tree appears to have too few nodes,
         * the bin is converted back to a plain bin. (The test triggers
         * somewhere between 2 and 6 nodes, depending on tree structure).
         */
        final void removeTreeNode(HashMap map, Node[] tab,
                                  boolean movable) {
              ...
        }
         /**
         * Calls find for root node.
         */
        final TreeNode getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }
        /**
         *通过比较hash值,递归的去遍历红黑树,
         compareableClassFor(Class k):
         判断实例k对应的类是否实现了Comparable接口,
         如果实现了该接口并在某些时候, 如果红黑树节点的元素are of the same "class C implements Comparable" type  
         *利用他们的compareTo()方法来比较大小,这里需要通过反射机制来check他们到底是不是属于同一个类,是不是具有可比较性.
         */
        final TreeNode find(int h, Object k, Class kc) {
            TreeNode p = this;
            do {
                int ph, dir; K pk;
                TreeNode pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }
        ...
    }

你可能感兴趣的:(HashMap源码阅读)