Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重塑术_Java_Collections_Linkedhashmap - Fatal编程技术网

Java 重塑术

Java 重塑术,java,collections,linkedhashmap,Java,Collections,Linkedhashmap,如何在FileOutputStream、DataOutputStream和writeObject()的帮助下重写removeEldestEntry方法以将最旧的条目保存到文件中。代码 下面是一个例子: import java.util.*; public class level1 { private static final int max_cache = 50; private Map cache = new LinkedHashMap(max_cache, .75F, true) {

如何在
FileOutputStream
DataOutputStream
writeObject()
的帮助下重写
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());

    }
import java.util.*;
公营一级{
私有静态最终int max_缓存=50;
私有映射缓存=新LinkedHashMap(最大缓存,.75F,真){
受保护的布尔重构(Map.Entry最早){
返回大小()>最大缓存;
}
};
公共级别1(){
对于(int i=1;i<52;i++){
String String=String.valueOf(i);
cache.put(string,string);
System.out.println(“\rCache size=“+cache.size()+
“\t当前值=“+i+”\t当前值=”+
cache.get(字符串)+“\t缓存中的值=”+
cache.values());
}
  • 调用
    super.removeeldestentiry
  • 如果项目已删除,请打开OutputStream
  • 写出对象
  • 从超级调用返回布尔值

您的代码已基本完成:

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

异常未处理java.io.FileNLTFoundException这是我在
伪代码中提到的。看起来像源代码,但不包括膨胀的异常处理…调用super.removeEldestEntry(最旧)不正确因为它在super中的实现总是返回false。@Avishay_uu是对的。我编辑了这个示例,以使其更符合OP最初的设置(某种最大缓存大小)常见的代码风格惯例是在所有大写字母中写入MAX_CACHE,因为它是一个静态的final/常量。正如公认答案中的一条注释正确指出的那样,这是不正确的,因为
super。Removeedestentiry
将始终返回
false