实现:
重写removeEldestEntry方法,MAX_ENTRIES规定缓存10个
public class LinkedHashMapDemo extends LinkedHashMap{
private static final long serialVersionUID = 6918023506928428613L;
private static int MAX_ENTRIES = 10;
public static int getMAX_ENTRIES() {
return MAX_ENTRIES;
}
public static void setMAX_ENTRIES(int max_entries) {
MAX_ENTRIES = max_entries;
}
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
}
public class LinkedDemo {
public static void main(String[] args) {
Map<String,String> linkedMap = (Map) new LinkedHashMapDemo();
for (int i = 1; i <= 50; i++) {
linkedMap.put(String.valueOf(i),String.valueOf(i));
}
int j = 1;
for (Map.Entry entry : linkedMap.entrySet()) {
System.out.print(entry.getKey()+ " " +entry.getValue()+" ");
if(j%10==0){
System.out.println();
}
j++;
}
}
}
41 41 42 42 43 43 44 44 45 45 46 46 47 47 48 48 49 49 50 50