両方のHashMapにコンテナを使用して、両方が同じオブジェクトグラフに属するようにすることができます。そうしないと、オブジェクトグラフが再作成されたときに、Javaはそれらが同じオブジェクトであると判断できません。結局のところ、それらをシリアル化し、個別に逆シリアル化しますね。
public class Container implements Serializable {
private Map<Object, Object> hashMapFoo ;
private Map<Object, Object> hashMapBar;
//...
}
コンテナをシリアル化して逆シリアル化する場合、ObjectInputStreamとObjectOutputStreamはオブジェクトグラフをシリアル化/逆シリアル化する間、参照を保持するため、参照は期待どおりである必要があります。
例:
これは私のために働きます:
public static void test() {
class Container implements Serializable {
Map<String,StringBuilder> map1 = new HashMap<String, StringBuilder>();
Map<String,StringBuilder> map2 = new HashMap<String, StringBuilder>();
}
try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("jedis.bin"))){
StringBuilder text = new StringBuilder("Hello Elvis");
Container container = new Container();
//same object in two different maps
container.map1.put("one", text);
container.map2.put("one", text);
out.writeObject(container);
}catch(IOException e) {
System.out.println(e.getMessage());
}
try(ObjectInputStream in = new ObjectInputStream(new FileInputStream("jedis.bin"))) {
Container container = (Container) in.readObject();
StringBuilder text1 = container.map1.get("one");
StringBuilder text2 = container.map2.get("one");
assert text1 == text2 : "text1 and tex2 are not the same reference";
}catch(Exception e) {
System.out.println(e.getMessage());
}
}