2011-01-27 63 views
3

如何在FileOutputStream,DataOutputStreamwriteObject()的幫助下覆蓋removeEldestEntry方法將最老的條目保存到文件中。碼。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()); 

    } 
+0

通用的代碼風格慣例將有MAX_CACHE寫在全部大寫,因爲它是一個靜態的最後的/不變。 – 2012-01-17 21:53:15

回答

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

未處理的異常java.io.FileNltFoundException – BraginiNI 2011-01-27 13:59:09

1
  • 呼叫super.removeEldestEntry
  • 如果已刪除項目開放的OutputStream
  • 寫出對象
  • 返回從超級呼叫布爾。
+0

正如接受的答案中的一個評論正確地指出的那樣,這是不正確的,因爲`super.removeEldestEntry`將*總是*返回`false`。 – 2013-09-10 17:58:00

相關問題