LinkedHashMap继承自HashMap,HashMap是无序的,而LinkedHashMap则利用双向非循环结构保持了插入节点的顺序(有两种顺序,插入顺序和访问顺序,后面解释)。
建议先搞明白HashMap的原理再看LinkedHashMap,Java集合源码分析-HashMap。
LinkedHashMap类图
和HashMap不同的地方在于它通过改造newNode方法和添加下面三个方法:
void afterNodeAccess(Node p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node p) { }
LinkedHashMap成员变量和构造器
LinkedHashMap继承了HashMap的所有的非private的变量,而且还多出来三个变量:
transient LinkedHashMap.Entry head;
transient LinkedHashMap.Entry tail;
final boolean accessOrder;
head和tail很简单,分别是头结点和尾节点,不解释,但是accessOrder就需要解释下了。accessOrder,看它的字面意思是访问顺序,那么就跟LinkedHashMap的节点顺序有关了,默认accessOrder是false,表示LinkedHashMap的节点顺序和插入顺序是一样的,如果accessOrder为true,那么在get方法中会调用afterNodeAccess
方法,看下这个方法的源码:
void afterNodeAccess(Node e) { // move node to last
LinkedHashMap.Entry last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry p =
(LinkedHashMap.Entry)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;
}
}
这个方法做的操作是将get访问的节点掐出来并挪到尾节点,这就是所谓的访问顺序,想想跟插入顺序的区别。java.util包下的集合的迭代器遍历都是fail-fast的,遍历时候更改集合的结构会抛出ConcurrentModificationException,一般来说get查询不会更改集合的结构,但是accessOrder为true的LinkedHashMap的get查询会更改集合的结构,可以看到上面代码的最后一行对modCount进行了加一操作。所以,如果LinkedHashMap的accessOrder为true,那么在迭代器遍历的时候千万别使用get方法。
举个例子:
Map linkedHashMap = new LinkedHashMap<>(16, 0.75f, true);
linkedHashMap.put("1", "callme1");
linkedHashMap.put("2", "callme2");
linkedHashMap.put("3", "callme3");
linkedHashMap.put("4", "callme4");
System.out.println("默认插入顺序:");
Set> set = linkedHashMap.entrySet();
Iterator> iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry entry = iterator.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
System.out.println("通过get方法,导致key为1对应的Entry挪到尾部");
linkedHashMap.get("2");
Set> set2 = linkedHashMap.entrySet();
Iterator> iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry entry = iterator2.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
LinkedHashMap比HashMap的构造器多了一个:
public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
可以看出这个构造器只是来处理accessOrder 而已。
LinkedHashMap节点类
static class Entry extends HashMap.Node {
Entry before, after;
Entry(int hash, K key, V value, Node next) {
super(hash, key, value, next);
}
}
可以看到LinkedHashMap节点类继承自HashMap节点类,来复习下HashMap的节点类:
static class Node implements Map.Entry {
final int hash;
final K key;
V value;
Node next;
}
LinkedHashMap节点类多了before和after两个属性,注意after和next两者区别,不需要解释了,通过before和after保持LinkedHashMap的有序性。
put
为了保持有序性,LinkedHashMap的put操作和HashMap的put有三点不同:
第一点不同是生成新节点的方法newNode不同(调用这个方法表示表中不存在重复key节点),LinkedHashMap多调用了一个方法linkNodeLast:
private void linkNodeLast(LinkedHashMap.Entry p) {
LinkedHashMap.Entry last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
很简单,只是将新节点插入到顺序表的尾部。
第二点不同是,如果表中存在和要插入节点的key相同的节点,覆盖之后会调用afterNodeAccess方法,前面介绍过,很简单。
第三点不同是LinkedHashMap在插入的最后一步调用了afterNodeInsertion(boolean evict)方法:
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;
}
从代码里可以看出,afterNodeInsertion试图将最老的节点即头结点删除,但是removeEldestEntry永远返回false,所以afterNodeInsertion什么都不会干的。afterNodeInsertion有什么卵用吗?这个removeEldestEntry方法应该需要用户重写的,下面的测试代码:
final int MAX_ENTRIES = 8;
LinkedHashMap lhm = new LinkedHashMap(MAX_ENTRIES, 0.75F, false) {
protected boolean removeEldestEntry(Map.Entry eldest) {
if (size() > MAX_ENTRIES) {
if (isImportant(eldest)) {
//Handle an important entry here, like reinserting it to the back of the list
this.remove(eldest.getKey());
this.put(eldest.getKey(), eldest.getValue());
//removeEldestEntry will be called again, now with the next entry
//so the size should not exceed the MAX_ENTRIES value
//WARNING: If every element is important, this will loop indefinetly!
} else {
return true; //Element is unimportant
}
return false; //Size not reached or eldest element was already handled otherwise
}
return false; //Size not reached or eldest element was already handled otherwise
}
};
lhm.put(1, "1");
lhm.put(2, "2");
lhm.put(3, "3");
lhm.put(4, "4");
lhm.put(5, "5");
lhm.put(6, "6");
lhm.put(7, "7");
lhm.put(8, "8");
lhm.put(9, "9");
lhm.put(10, "10");
System.out.println("" + lhm);
结果输出如图所示:
可以看到map中最多只有8个节点,超出的话会把老的删除。
remove
LinkedHashMap的删除比HashMap的删除多了一步afterNodeRemoval:
void afterNodeRemoval(Node e) { // unlink
LinkedHashMap.Entry p =
(LinkedHashMap.Entry)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;
}
主要处理before和after,很简单。
遍历
HashMap遍历的核心类是HashIterator,而LinkedHashMap遍历的核心类是LinkedHashIterator,很简单,核心方法是nextNode:
final LinkedHashMap.Entry nextNode() {
LinkedHashMap.Entry e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
current = e;
next = e.after;
return e;
}
保持有序遍历最关键的一行代码是第八行:next = e.after;
。
最后附一张LinkedHashMap的底层结构图,双向非循环链表: