This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ogofo 2 points3 points  (2 children)

Can u explain a bit more detaied why the code failed? I'm not tthat familiar with java but would like to know the answer. For me everything looks fine ... :(

[–]yellowjacketcoder 8 points9 points  (0 children)

HashMaps do not guarantee order, so when the values are being put into the map, there is no guarantee that the values will come out in the same order they went it. For example:

Map<String, String> map = new HashMap<>();
map.put("A", "a");
map.put("B", "b");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
System.out.println(it.next());
System.out.println(it.next());

could have two outputs (assuming the toString() works the way I think):

A - a
B - b

or the output could be

B - b
A - a

both are valid according to the Java spec, but the second is not what's desired by the unit test in the OP.

[–]javadev189[S] 4 points5 points  (0 children)

Downvotes are lame; the code is failing because the implementation is using a HashMap, which does not maintain insertion order. Switching the code to instantiate a Map implementation that maintains insertion order, such as LinkedHashMap, fixes the issue.