简介
我们知道HashMap的变量顺序是不可预测的,这意味着便利的输出顺序并不一定和HashMap的插入顺序是一致的。这个特性通常会对我们的工作造成一定的困扰。为了实现这个功能,我们可以使用LinkedHashMap。
LinkedHashMap详解
先看下LinkedHashMap的定义:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
LinkedHashMap继承自HashMap,所以HashMap的所有功能在LinkedHashMap都可以用。
LinkedHashMap和HashMap的区别就是新创建了一个Entry:
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);
}
}
这个Entry继承自HashMap.Node,多了一个before,after来实现Node之间的连接。
通过这个新创建的Entry,就可以保证遍历的顺序和插入的顺序一致。
插入
下面看一个LinkedHashMap插入的例子:
@Test
public void insertOrder(){