Java通过LinkedHashMap实现LRU -----学习笔记
import java.util.*;
public class Test<K,V> extends LinkedHashMap<K,V> {
private int capacity;
public Test(int capacity){
super();
this.capacity=capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
public static void main(String[] args) {
Test<Integer,Integer> test = new Test<>(3);
test.put(1,2);
test.put(2,3);
test.put(3,4);
for(Map.Entry<Integer,Integer> temp : test.entrySet()){
System.out.println(temp.getKey()+" "+temp.getValue());
}
System.out.println("================================");
test.put(4,5);
for(Map.Entry<Integer,Integer> temp : test.entrySet()){
System.out.println(temp.getKey()+" "+temp.getValue());
}
System.out.println("================================");
System.out.println(test.get(2));
System.out.println("================================");
for(Map.Entry<Integer,Integer> temp : test.entrySet()){
System.out.println(temp.getKey()+" "+temp.getValue());
}
}
}