前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java LinkedHashMap 源码分析

Java LinkedHashMap 源码分析

作者头像
Yano_nankai
发布2019-02-25 16:25:37
4630
发布2019-02-25 16:25:37
举报
文章被收录于专栏:二进制文集二进制文集

Demo

@Test
public void testLinkedHashMap() {
    Map<String, Integer> map = new LinkedHashMap<String, Integer>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
            return size() > 3;
        }
    };
    map.put("1", 1);
    map.put("2", 2);
    map.put("3", 3);
    map.put("4", 4);
    for(Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}

输出

2: 2
3: 3
4: 4

迭代输出能够保持插入顺序。

分析

内部结构

LinkedHashMap继承自HashMap,内部额外维护了一个Entry的双向链表,用于记录访问和插入顺序。官方注释:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.

需要注意:如果某个key已经存在,再次put不会改变插入的顺序。

LinkedHashMap.Entry

LinkedHashMap.Entry只是比HashMap.Node多了两个指针而已,LinkedHashMap.Entry直接就是双向链表的元素了。

/**
 * HashMap.Node subclass for normal LinkedHashMap entries.
 */
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}

/**
 * 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;

重要函数

HashMap中定义的3个函数:

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

LinkedHashMap继承于HashMap,重写了这3个函数。这3个函数分别为在访问节点、插入节点、删除节点时做一些事情。

在对LinkedHashMap进行put操作时,执行的是HashMap的put方法,多态调用LinkedHashMap的上述3个函数。

HashMap 的 put 方法

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 {
        Node<K,V> e; K k;
        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;
}

LinkedHashMap 的 get 方法

public V get(Object key) {
    Node<K,V> e;
    if ((e = getNode(hash(key), key)) == null)
        return null;
    if (accessOrder)
        afterNodeAccess(e);
    return e.value;
}

可以看到其核心为这3个函数。

afterNodeAccess

void afterNodeAccess(Node<K,V> e) { // move node to last
    LinkedHashMap.Entry<K,V> last;
    if (accessOrder && (last = tail) != e) {
        LinkedHashMap.Entry<K,V> p =
            (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
        p.after = null;
        if (b == null)
            head = a;
        else
            b.after = a;
        if (a != null)
            a.before = b;
        else
            last = b;
        if (last == null)
            head = p;
        else {
            p.before = last;
            last.after = p;
        }
        tail = p;
        ++modCount;
    }
}

afterNodeInsertion

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

afterNodeRemoval

void afterNodeRemoval(Node<K,V> e) { // unlink
    LinkedHashMap.Entry<K,V> p =
        (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
    p.before = p.after = null;
    if (b == null)
        head = a;
    else
        b.after = a;
    if (a == null)
        tail = b;
    else
        a.before = b;
}

LinkedHashMap 和 HashMap 对比

LinkedHashMap 的应用场景?

  • 需要记录插入顺序、访问顺序时
  • 可以做缓存使用,因为可以重写removeEldestEntry,使map保持在一定的容量

LinkedHashMap 的 put 操作时间复杂度?

时间复杂度应该是o(n),其中n为容量。因为put时在找到对应的value后,需要维护双向链表。

现在有一个疑问,LinkedHashMap存在有什么意义?既然要维护一个双向链表,就不可能做到HashMap o(1)的时间复杂度。LinkedHashMap和直接使用双向链表有什么区别?

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.01.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Demo
  • 分析
    • 内部结构
      • LinkedHashMap.Entry
        • 重要函数
          • HashMap 的 put 方法
          • LinkedHashMap 的 get 方法
          • afterNodeAccess
          • afterNodeInsertion
          • afterNodeRemoval
      • LinkedHashMap 和 HashMap 对比
        • LinkedHashMap 的应用场景?
          • LinkedHashMap 的 put 操作时间复杂度?
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档