从 Map 到 HashMap 到 LinkedHashMap

java 从 Map 到 HashMap 到 LinkedHashMap

Map 接口

Map 是 java 容器的基础接口,提供按照 kv 方式存取数据的能力。Map 定义了一系列的操作,以及一个内部接口 Map.Entry ,Entry 表示一个 kv 对 :

int size()
boolean isEmpty()
boolean containKey(Object)
boolean containValue(Object)
V get(Object)
V put(K, V)
V remove(Object)
...
Entry<K, V> {
    K getKey()
    V getValue()
    V setValue(V)
    ...
}

HashMap

HashMap 是 Map 的一种实现方式,内部通过 hashCode 把数据分布到对应的数组(表,table)位置上。HashMap 内部实现采用了很高效的方法来进行 hash。HashMap 有几个关键的因素:容量、负载因子、红黑树。

表的容量为 2^n ,初始默认值为 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4 ,每次增长时直接左移 1 。在进行 hash 时,直接用 k 的 hashCode 进行 hashCode & (table.lenght - 1) ,这样的方式不需要使用 mod 运算,全部使用位运算, 速度非常快。

当多个 k 对应到表的同一个位置时,需要进行扩展处理。HashMap 创建 HashMap.Node<K, V> 继承了 Map.Entry,并设计为链表方式,可在后面追加元素。

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    ...
}

要留意一点:Node 里面记录了数据项原始的 hash 值,一方面是减少计算 hash 的开销,另一方面的避免了因为 key 对象的修改导致的 hash 结果的变化。

但链表方式在追加或查找元素时速度比较慢,需要 O(n) 复杂度,因此 HashMap 在此基础上做了进一步的优化(jdk8),当一个链表的元素超过特定的数量 static final int TREEIFY_THRESHOLD = 8,将列表转换为红黑树 ,而小于特定的个数 static final int UNTREEIFY_THRESHOLD = 6; 时重新转为链表。

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
    ...
}

TreeNode 扩展的 LinkedHashMap 里面的 Entry 而不只是 Node,使得它可以应用于带链接的节点。TreeMap 也是基于红黑树的结构,而 TreeMap 要求 key 实现 Comparable 接口,但是 HashMap 没有此要求,它通过 key 的 hash 值和 key 本身的 class 是否支持 Comparable 来进行查找

/**
* Finds the node starting at root p with the given hash and key.
* The kc argument caches comparableClassFor(key) upon first use
* comparing keys.
*/
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
    TreeNode<K,V> p = this;
    do {
        int ph, dir; K pk;
        TreeNode<K,V> pl = p.left, pr = p.right, q;
        if ((ph = p.hash) > h)  // 当前节点 hash 比 key 大,左子树
            p = pl;
        else if (ph < h)        // 当前节点 hash 比 key 小,右子树
            p = pr;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;           // 找到了
        else if (pl == null)
            p = pr;             // hash 相等,只有右子树
        else if (pr == null)
            p = pl;             // hash 相等,只有左子树
        else if ((kc != null ||
                    (kc = comparableClassFor(k)) != null) &&
                    (dir = compareComparables(kc, k, pk)) != 0)
            p = (dir < 0) ? pl : pr;    // hash 相等,支持 Comparable 
        else if ((q = pr.find(h, k, kc)) != null)
            return q;
        else
            p = pl;
    } while (p != null);
    return null;
}

在进行 putremove 时,HashMap 对表项的元素数进行计算,自动转换。以下为 put 使用的 putVal 内部函数的部分代码

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 {
        /* tab[hash & (tab.length - 1)] 位置有数据项时 */
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;  // 相同的key,后面直接替换value
        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;
            }
        }
        ...
    }
}

当 HashMap 数据量较多,而表不变的话,会导致查找量加大,因此,HashMap 使用一个 loadFactor 变量来数据量占比到达多大时进行表扩容,这个值默认为 static final float DEFAULT_LOAD_FACTOR = 0.75f; ,用 loadFactor * table.length 得到一个数据量阈值 threshold 就是衡量当前数据量是否需要进行扩容的指标。

扩容也不能无限扩容,HashMap 里面设置了最大容量为 static final int MAXIMUM_CAPACITY = 1 << 30;(hashCode 为 int 类型,int 最大值为 2^31 -1)。到达表最大容量时,原来的表不变,只将 HashMap 的容量指标 threshold 改到 Interger.MAX_VALUE

扩容的 resize() 函数比较复杂,包括以下的流程:

1. 确定新容量,如果旧容量为0,则为默认的初始容量,否则为旧容量的2倍(左移1)
2. 创建新容量的表
3. 从旧表转移所有的的节点到新表

LinkedHashMap

LinkedHashMap 在 HashMap 的基础上,增加对顺序的记录(插入顺序或访问顺序 accessOrder)。这使用 LinkedHashMap 经常用来作为 LRU cache 的实现基础。

顺序的记录主要是通过 LinkedHashMap.Entry 实现:

static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    ...
}

before 指向此记录的前一记录,after 为此记录的后一记录,同时,LinkedHashMap 中记录了头部和尾部:

/**
 * The head (eldest) of the doubly linked list.
 */
transient LinkedHashMap.Entry<K,V> head;

/**
 * The tail (youngest) of the doubly linked list.
 */
transient LinkedHashMap.Entry<K,V> tail;

每次进行修改时,需要同时处理 tail 指向的元素,以保证顺序记录准确。

posted @ 2019-12-24 11:03  drop *  阅读(867)  评论(0编辑  收藏  举报