0

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()?

Nathan Merrill
  • 7,648
  • 5
  • 37
  • 56
  • If you have two entries in your hash map, you will get two values with `HashMap#getValues`. – Aurand Aug 14 '13 at 04:12
  • Why does getValues() return two pointers to the same object? If I wanted to iterate over the entries, I would iterate over the keySet, not over the values. – Nathan Merrill Aug 14 '13 at 04:15
  • Because that's how a HashMap works. Keys are unique, there is no guarantee of uniqueness on values. Returning just the unique values is more computationally expensive and is not general enough of a use case to be included. If you want a unique value set, you'll have to parse it yourself (possibly with a HashSet). – Aurand Aug 14 '13 at 04:20

1 Answers1

2
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.

Aurand
  • 5,487
  • 1
  • 25
  • 35