您可以为两个 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());
}
}