那么什么是LinkedHashMap的插入顺序和访问顺序呢?
插入顺序:是指LinkedHashMap在数据插入时的插入顺序;
比如说1,2,3,4…数据依次从小到大插入;
若按照插入顺序输出,输出结果就是1,2,3,4…
访问顺序:则是说同样按照插入1,2,3,4…从小到大有序的插入;
如果在插入后你随机访问了某个元素,那么那个元素则会排列到集合的最后一位
true: 基于访问顺序
public class LRUCache<K, V> extends LinkedHashMap {
private Integer initialCapacity;
public LRUCache (int initialCapacity) {
//initialCapacity 初始容量大小,使用无参构造方法时,此值默认是16
//loadFactor 加载因子,使用无参构造方法时,此值默认是 0.75f
//accessOrder false: 基于插入顺序 true: 基于访问顺序
super(initialCapacity, 0.75F, true);
this.initialCapacity = initialCapacity;
}
@Override
protected boolean removeEldestEntry (Entry eldest) {
return super.size() > initialCapacity;
}
public static void main (String[] args) {
LRUCache<String, String> data = new LRUCache<String, String>(3);
data.put("1", "A");
data.put("2", "B");
data.put("3", "C");
System.out.println(data.keySet()); //1,2,3
data.get("1");
System.out.println(data.keySet()); //2,3,1
data.get("2");
System.out.println(data.keySet());//3,1,2
}
}
false: 基于插入顺序
public class LRUCache<K, V> extends LinkedHashMap {
private Integer initialCapacity;
public LRUCache (int initialCapacity) {
//initialCapacity 初始容量大小,使用无参构造方法时,此值默认是16
//loadFactor 加载因子,使用无参构造方法时,此值默认是 0.75f
//accessOrder false: 基于插入顺序 true: 基于访问顺序
super(initialCapacity, 0.75F, false);
this.initialCapacity = initialCapacity;
}
@Override
protected boolean removeEldestEntry (Entry eldest) {
return super.size() > initialCapacity;
}
public static void main (String[] args) {
LRUCache<String, String> data = new LRUCache<String, String>(3);
data.put("1", "A");
data.put("2", "B");
data.put("3", "C");
System.out.println(data.keySet()); //1,2,3
data.put("4", "D");
System.out.println(data.keySet()); //2,3,4
data.put("3", "C");
System.out.println(data.keySet()); //2,3,4
data.put("5", "X");
System.out.println(data.keySet());//3,4,5
}
}