我有一个包含两个哈希映射的类,并希望加载存储类记录的完整对象。我尝试使用以下代码,但'load'方法给出错误“无法将变量分配给最终变量”
class records{
HashMap<String, HashMap<String, Integer> > Map1 = new HashMap <>();
HashMap<String, HashMap<String, Integer> > Map2 = new HashMap <>();
public boolean store(File f) {
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this); // THIS WORKED
oos.close();
fos.close();
} catch (IOException ex) {
return false;
}
return true;
}
public boolean load(File f) {
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
this = (records) ois.readObject(); // THIS LINE GIVING ERROR
ois.close();
fis.close();
} catch (IOException e) {
return false;
} catch (ClassNotFoundException e) {
return false;
}
return true;
. . .
}
我是否需要像Load/Store Objects in file in Java一样分别编写和读取两个hashMap元素?
答案 0 :(得分:0)
您无法为此分配变量。而是设置单个实例变量或创建新引用。
public records load(File f) {
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
records r1= (records) ois.readObject(); // THIS LINE GIVING ERROR
ois.close();
fis.close();
return r1;
} catch (IOException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
}
return null;
. . .
}