如何覆盖removeEldestEntry方法将最老的条目保存到文件?还有如何像在LinkedHashMap中那样限制文件的大小。这里是代码:removeEldestEntry覆盖
import java.util.*;
public class level1 {
private static final int max_cache = 50;
private Map cache = new LinkedHashMap(max_cache, .75F, true) {
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > max_cache;
}
};
public level1() {
for (int i = 1; i < 52; i++) {
String string = String.valueOf(i);
cache.put(string, string);
System.out.println("\rCache size = " + cache.size() +
"\tRecent value = " + i + " \tLast value = " +
cache.get(string) + "\tValues in cache=" +
cache.values());
}
我试图用FileOutputStream中:
private Map cache = new LinkedHashMap(max_cache, .75F, true) {
protected boolean removeEldestEntry(Map.Entry eldest) throws IOException {
boolean removed = super.removeEldestEntry(eldest);
if (removed) {
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(eldest.getValue());
oos.close();
}
return removed;
}
但我已经获得了一个错误
错误(15,27):removeEldestEntry(java.util.Map .Entry)in不能覆盖java.util.LinkedHashMap中的removeEldestEntry(java.util.Map.Entry);重写的方法不会抛出java.io.IOException
没有IOExecptio编译器要求处理IOexception和Filenotfoundexception。 也许有另一种方式存在?请告诉我示例代码,我是java中的新成员,并试图理解2级缓存的基本原理。 Thx
BTW super.removeEldestEntry(长子)始终返回false。当您想要最老的条目被丢弃时,您必须覆盖它以返回true。您的文件t.tmp只会保留最后一个被删除的条目。这是你的意图吗? – 2011-01-27 15:49:47