Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use a container for both your HashMaps, so that they both belong to the same object graph, otherwise, when the object graph is recreated, Java has no way to determine that they are the same object. After all, you serialize them and deserialize them independently, isn't so?</p> <pre><code>public class Container implements Serializable { private Map&lt;Object, Object&gt; hashMapFoo ; private Map&lt;Object, Object&gt; hashMapBar; //... } </code></pre> <p>If you serialize the container, and deserialize it back, the references should be what you were expecting, because the ObjectInputStream and ObjectOutputStream keep references to them while serializing/deserializing your object graph.</p> <h2>Example:</h2> <p>This works for me:</p> <pre><code>public static void test() { class Container implements Serializable { Map&lt;String,StringBuilder&gt; map1 = new HashMap&lt;String, StringBuilder&gt;(); Map&lt;String,StringBuilder&gt; map2 = new HashMap&lt;String, StringBuilder&gt;(); } 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()); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload