public class LRULinkedHashMap<K,V> extends LinkedHashMap{
//缓冲容量
private int capacity;
public LRULinkedHashMap(int capacity){
super(16,0.75f,true);
this.capacity = capacity;
}
//重写removeEldestEntry 返回值代表是否需要删除最老的节点的判断
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
boolean sign = size() > capacity;
if(sign){
System.out.println("要删除地是:"+eldest);
}
return sign;
}
}
public static void main(String[] args) {
LRULinkedHashMap<String,Integer> map = new LRULinkedHashMap(4);
map.put("111",111);
map.put("222",222);
map.put("333",333);
map.put("444",444);
map.put("555",555);
Iterator<Map.Entry<String,Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,Integer> entry = iterator.next();
System.out.println(entry.getKey()+ "=="+ entry.getValue());
}
}
要删除地是:111=111
222==222
333==333
444==444
555==555