每次调用get或put,收到影响的条目将从当前位置删除,并放到条目链表的尾部(只影响条目在链表中的位置)
可以实现“最近最少使用”的原则。重写removeEldestEntry
假如你希望将访问频率高的放到内存中,频率低的删除。只需删除链表的前面条目即可;
当然还可以对eldest条目进行评估,以此决定是否应该删除。
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
public static void main(String[] args) {
Map<String,Integer> dd=new LinkedHashMap<String,Integer>(10,0.75f,true){
// return true 删除频率低的
protected boolean removeEldestEntry(Map.Entry<String,Integer> eldest) {
//eldest == 22:2 22是最先放进来的
return size()>3;
}
};
dd.put("22",2);
dd.put("55",5);
dd.put("66",6);
dd.get("22");//调用22 ,那么55就是频率低的,在put “77”时 ,size()>3 返回true ;因此删除 “55”
dd.put("77",7);
System.out.println(dd.keySet());//out : [66, 22, 77]
dd.get("66");
System.out.println(dd.keySet());//out : [22, 77, 66]
}
下面是优先级队列PriorityQueue;迭代不是按照元素的排列顺序访问。删除总是删掉列表中优先级数最小的那个元素
public static void main(String[] args) {
PriorityQueue<LocalDate> pq=new PriorityQueue<>();
pq.add(LocalDate.of(1906,12,9));
pq.add(LocalDate.of(1815,12,9));
pq.add(LocalDate.of(1903,12,9));
pq.add(LocalDate.of(1910,12,9));
System.out.println("Iterating elements...");
for (LocalDate ld:pq)
System.out.println(ld);//迭代不是按照元素的排列顺序访问。
System.out.println("Removing elements...");
while (!pq.isEmpty())
System.out.println(pq.remove());//删除总是删掉列表中优先级数最小的那个元素
}