[关闭]
@Yano 2019-09-20T10:45:51.000000Z 字数 3822 阅读 1484

Java LinkedHashMap 源码分析

Java


公众号

coding 笔记、点滴记录,以后的文章也会同步到公众号(Coding Insight)中,希望大家关注^_^

https://github.com/LjyYano/Thinking_in_Java_MindMapping

Demo

  1. @Test
  2. public void testLinkedHashMap() {
  3. Map<String, Integer> map = new LinkedHashMap<String, Integer>() {
  4. @Override
  5. protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
  6. return size() > 3;
  7. }
  8. };
  9. map.put("1", 1);
  10. map.put("2", 2);
  11. map.put("3", 3);
  12. map.put("4", 4);
  13. for(Map.Entry<String, Integer> entry : map.entrySet()) {
  14. System.out.println(entry.getKey() + ": " + entry.getValue());
  15. }
  16. }

输出

  1. 2: 2
  2. 3: 3
  3. 4: 4

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

分析

内部结构

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

  1. 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直接就是双向链表的元素了。

  1. /**
  2. * HashMap.Node subclass for normal LinkedHashMap entries.
  3. */
  4. static class Entry<K,V> extends HashMap.Node<K,V> {
  5. Entry<K,V> before, after;
  6. Entry(int hash, K key, V value, Node<K,V> next) {
  7. super(hash, key, value, next);
  8. }
  9. }
  10. /**
  11. * The head (eldest) of the doubly linked list.
  12. */
  13. transient LinkedHashMap.Entry<K,V> head;
  14. /**
  15. * The tail (youngest) of the doubly linked list.
  16. */
  17. transient LinkedHashMap.Entry<K,V> tail;

重要函数

HashMap中定义的3个函数:

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

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

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

HashMap 的 put 方法

  1. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  2. boolean evict) {
  3. Node<K,V>[] tab; Node<K,V> p; int n, i;
  4. if ((tab = table) == null || (n = tab.length) == 0)
  5. n = (tab = resize()).length;
  6. if ((p = tab[i = (n - 1) & hash]) == null)
  7. tab[i] = newNode(hash, key, value, null);
  8. else {
  9. Node<K,V> e; K k;
  10. if (p.hash == hash &&
  11. ((k = p.key) == key || (key != null && key.equals(k))))
  12. e = p;
  13. else if (p instanceof TreeNode)
  14. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  15. else {
  16. for (int binCount = 0; ; ++binCount) {
  17. if ((e = p.next) == null) {
  18. p.next = newNode(hash, key, value, null);
  19. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  20. treeifyBin(tab, hash);
  21. break;
  22. }
  23. if (e.hash == hash &&
  24. ((k = e.key) == key || (key != null && key.equals(k))))
  25. break;
  26. p = e;
  27. }
  28. }
  29. if (e != null) { // existing mapping for key
  30. V oldValue = e.value;
  31. if (!onlyIfAbsent || oldValue == null)
  32. e.value = value;
  33. afterNodeAccess(e);
  34. return oldValue;
  35. }
  36. }
  37. ++modCount;
  38. if (++size > threshold)
  39. resize();
  40. afterNodeInsertion(evict);
  41. return null;
  42. }

LinkedHashMap 的 get 方法

  1. public V get(Object key) {
  2. Node<K,V> e;
  3. if ((e = getNode(hash(key), key)) == null)
  4. return null;
  5. if (accessOrder)
  6. afterNodeAccess(e);
  7. return e.value;
  8. }

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

afterNodeAccess

  1. void afterNodeAccess(Node<K,V> e) { // move node to last
  2. LinkedHashMap.Entry<K,V> last;
  3. if (accessOrder && (last = tail) != e) {
  4. LinkedHashMap.Entry<K,V> p =
  5. (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
  6. p.after = null;
  7. if (b == null)
  8. head = a;
  9. else
  10. b.after = a;
  11. if (a != null)
  12. a.before = b;
  13. else
  14. last = b;
  15. if (last == null)
  16. head = p;
  17. else {
  18. p.before = last;
  19. last.after = p;
  20. }
  21. tail = p;
  22. ++modCount;
  23. }
  24. }

afterNodeInsertion

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

afterNodeRemoval

  1. void afterNodeRemoval(Node<K,V> e) { // unlink
  2. LinkedHashMap.Entry<K,V> p =
  3. (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
  4. p.before = p.after = null;
  5. if (b == null)
  6. head = a;
  7. else
  8. b.after = a;
  9. if (a == null)
  10. tail = b;
  11. else
  12. a.before = b;
  13. }

LinkedHashMap 和 HashMap 对比

LinkedHashMap 的应用场景?

LinkedHashMap 的 put 操作时间复杂度?

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

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

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注