Search code examples
javaxstream

Iteration running more than once per value LinkedHashMap


I have XStream building a Linked Hash Map for me using this xml:

<linked-hash-map>
 <entry>
  <string>#!/masterofsoundtrack/broadcast</string>
  <broadcast>
    <attributes class="linked-hash-set"/>
    <url>#!/masterofsoundtrack/broadcast</url>
    <name>MasterofSoundtrack</name>
    <description></description>
    <startsClosed>false</startsClosed>
  </broadcast>
 </entry>
 <entry>
  <string>MasterofSoundtrack</string>
  <broadcast reference="../../entry/broadcast"/>
 </entry>
</linked-hash-map>

Note: if you don't understand what XStream is supposed to do, it converts XML to objects. The above XML means to have a linked hash map, with two keys both pointing to the same object.

However, when I iterate through this using the following code:

for(Broadcast broadcast: map.getValues()){
    managers.add(new Manage(broadcast));
}

I am running the managers.add() line twice. If I debug and look at the map, they have different IDs, but look identical. Is this a bug with XStream, or something I don't understand with getValues()?


Solution

  • HashMap<String, Object> map = new HashMap<>();
    Object o = new Object;
    map.put("1", o);
    map.put("2", o);
    System.out.print(map.values().size()) //prints 2
    

    As long as the keys are unique, you will get a separate entry for each value, regardless of value equality.