在此代码中有一些错误:
错误(18,40):未报告的异常java.io.FileNotFoundException;必须捕获或声明为抛出错误(19,42):未报告的异常java.io.IOException;必须捕获或声明为抛出
但是当抛出FileNotFound和IOException异常时,编译器将显示此错误:
错误(15,27):removeEldestEntry(java.util.Map.Entry) in不能覆盖java.util.LinkedHashMap中的removeEldestEntry(java.util.Map.Entry);重写的方法不会抛出java.io.IOException
有什么问题吗?代码在这里:
package client;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
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) {
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;
}
};
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());
}
}发布于 2012-07-03 05:44:12
试试这个..。
package client;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;
public class Level1 {
private static final int max_cache = 50;
private Map cache = new LinkedHashMap(max_cache, .75F, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
boolean removed = super.removeEldestEntry(eldest);
if (removed) {
FileOutputStream fos;
try {
fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(eldest.getValue());
oos.close();
} catch (IOException ex) {
System.err.println("IOException!!");
} catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException!!");
}
}
return removed;
}
};
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());
}
}
}发布于 2011-01-27 14:22:23
您需要在您的FileNotFoundException方法中处理removeEldestEntry (句柄如in,捕获它并记录它)。当您覆盖一个方法时,您不允许在方法签名上添加新的异常,因为这样您的子类就不再可以替代您要子类的东西了。
否则,可以找到一种不同的方法来完成它,这样您的removeEldestEntry就可以将条目排队起来,其他的东西就可以读取队列,并对一个文件进行序列化。实际上,在阅读了Javadoc之后,似乎必须有一个更好的地方来放置这个逻辑,实际执行删除的代码可能是执行序列化的更好的地方。
https://stackoverflow.com/questions/4817398
复制相似问题