removeEldestEntry

Bra*_*iNI 3 java collections linkedhashmap

我怎么可以重写removeEldestEntry方法节约与帮助到文件最旧的条目FileOutputStream,DataOutputStreamwriteObject().码.

这是一个例子:

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

    }
Run Code Online (Sandbox Code Playgroud)

Chr*_*ach 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 这就是我在"伪代码"中提到的.看起来像Sourcecode,但不包括膨胀的Exceptionhandling ...... (3认同)