3

如何在 和 的帮助下覆盖将最旧removeEldestEntry条目保存到文件的方法 代码。FileOutputStreamDataOutputStreamwriteObject()

这是示例:

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());

    }
4

2 回答 2

8

您的代码几乎完成了:

private Map cache = new LinkedHashMap(max_cache, .75F, true) {
    protected boolean removeEldestEntry(Map.Entry eldest) {
       // Pseudo-Code 
       if(this.size() > MAX_CACHE_SIZE){
           FileOutputStream fos = new FileOutputStream("t.tmp");
           ObjectOutputStream oos = new ObjectOutputStream(fos);

           oos.writeObject(eldest.getValue());
           return true;
       } finally {
           oos.close();
           fos.close();
       }

       return false;
    }
};
于 2011-01-27T12:42:09.007 回答
1
  • 称呼super.removeEldestEntry
  • 如果删除了一个项目,则打开一个 OutputStream
  • 写出对象
  • 从超级调用返回布尔值。
于 2011-01-27T12:20:58.760 回答