LinkedHashMap 内部有一个嵌套类 Entry，它继承自 HashMap 中的 Node 类，如下：

static class Entry<K,V> extends HashMap.Node<K,V> {
Entry before, after;
Entry(int hash, K key, V value, Node next) {
super(hash, key, value, next);
}
}

static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node next;
Node(int hash, K key, V value, Node next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
// …
}

/**
*/

/**
* The tail (youngest) of the doubly linked list.
*/

/**
* The iteration ordering method for this linked hash map: true
* for access-order, false for insertion-order.
*/
final boolean accessOrder;

/**
* Constructs an empty insertion-ordered LinkedHashMap instance
* with the default initial capacity (16) and load factor (0.75).
*/
super();
accessOrder = false;
}

super(initialCapacity);
accessOrder = false;
}

accessOrder = false;
}

public LinkedHashMap(Map<? extends K, ? extends V> m) {
super();
accessOrder = false;
putMapEntries(m, false);
}

boolean accessOrder) {
this.accessOrder = accessOrder;
}

put 方法

LinkedHashMap 本身没有实现 put 方法 ，它通过调用父类（HashMap）的方法来进行读写操作。这里再贴下 HashMap 的 put 方法：

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n – 1) & hash]) == null)
// 新的 bin 节点
tab[i] = newNode(hash, key, value, null);
else {
Node 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)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;
}

Node newNode(int hash, K key, V value, Node next) {
return new Node(hash, key, value, next);
}

Node newNode(int hash, K key, V value, Node e) {
// 将新节点连接到列表末尾
return p;
}

// link at the end of list
tail = p;
// list 为空
if (last == null)
else {
// 将新节点插入到 list 末尾
p.before = last;
last.after = p;
}
}

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

void afterNodeAccess(Node e) { // move node to last
// accessOrder 为 true 表示访问顺序
if (accessOrder && (last = tail) != e) {
// p 为访问的节点，b 为其前驱，a 为其后继
(LinkedHashMap.Entry)e, b = p.before, a = p.after;
p.after = null;
// p 是头节点
if (b == null)
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}

get 方法

LinkedHashMap 重写了 HashMap 的 get 方法，主要是为了维持访问顺序，代码如下：

public V get(Object key) {
Node e;
if ((e = getNode(hash(key), key)) == null)
return null;
// 若为访问顺序，将访问的节点移到列表末尾
if (accessOrder)
afterNodeAccess(e);
return e.value;
}

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

// LinkedHashMap 中默认的返回值为 false，即这里的 removeNode 方法不执行
protected boolean removeEldestEntry(Map.Entry eldest) {
return false;
}

removeNode 方法是父类 HashMap 中的。

final Node removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable
) {
Node[] tab; Node p; int n, index;
// table 不为空，且给的的 hash 值所在位置不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n – 1) & hash]) != null) {
Node node = null, e; K k; V v;
// 给定 key 对应的节点，在数组中第一个位置
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
// 给定的 key 所在位置为红黑树或链表
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);
}
}
// 删除节点
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;
}

afterNodeRemoval 方法在 HashMap 中的实现也是空的：

void afterNodeRemoval(Node p) { }

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

Map map = new HashMap();
map.put(“bush”, “a”);
map.put(“obama”, “b”);
map.put(“trump”, “c”);
map.put(“lincoln”, “d”);
System.out.println(map);

// 输出结果（无序）：
// {obama=b, trump=c, lincoln=d, bush=a}

map.put(“bush”, “a”);
map.put(“obama”, “b”);
map.put(“trump”, “c”);
map.put(“lincoln”, “d”);
System.out.println(map);

// 输出结果（插入顺序）：
// {bush=a, obama=b, trump=c, lincoln=d}

Map map = new LinkedHashMap(2, 0.75f, true);
map.put(“bush”, “a”);
map.put(“obama”, “b”);
map.put(“trump”, “c”);
map.put(“lincoln”, “d”);
System.out.println(map);

map.get(“obama”);
System.out.println(map);

// 输出结果（插入顺序）：
// {bush=a, obama=b, trump=c, lincoln=d}

// 访问 obama 后，obama 移到了末尾
// {bush=a, trump=c, lincoln=d, obama=b}

private static class LRUCache<K, V> extends LinkedHashMap<K, V> {
private int capacity;

public LRUCache(int capacity) {
super(16, 0.75f, true);
this.capacity = capacity;
}

@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
}

LRUCache<String, String> lruCache = new LRUCache(2);
lruCache.put(“bush”, “a”);
lruCache.put(“obama”, “b”);
lruCache.put(“trump”, “c”);
System.out.println(lruCache);

// 输出结果：

// {obama=b, trump=c}

1. LinkedHashMap 继承自 HashMap，其结构可以理解为「双链表 + 散列表」；

2. 可以维护两种顺序：插入顺序或访问顺序；

3. 可以方便的实现 LRU 缓存；

4. 线程不安全。

Stay hungry, stay foolish.