开发者

removeEldestEntry

How can I override removeEldestEntry method to saving eldest entry to file with help of FileOutputStream, DataOutputStream and writeObject(). Code.

Here's example:

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.val开发者_StackOverflow中文版ues());

    }


Your code is almost complete:

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;
    }
};


  • Call super.removeEldestEntry
  • If an item was removed open a OutputStream
  • Write out the object
  • Return the boolean from the super call.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜