If I have a hash map and iterate over the objects repeatedly, is it correct that I'm not guaranteed the same order for every call? For example, could the following print two lines that differ from each other:
Map<String,Integer> map = new HashMap<String,Integer>()
{{ put("a", 1); put("b", 2); put("c", 3); }};
System.out.println(map);
System.out.println(map);
And is this the case for sets and collections in general? If so, what's the best way in case you have to iterate twice over the same collection in the same order (regardless of what order that is)? I guess converting to a list.
The contracts of Map
and Set
do not make any guarantees about iteration order, but those of SortedSet
and SortedMap
(implemented by TreeMap
and TreeSet
) do.
Furthermore, even the non-sorted implementations generally behave deterministically and have a repeatable iteration order for each specific instance, as long as it's not modified in any way. However, that's an implementation detail and should not be relied upon.
you're correct, the order of a map is not guaranteed. you might want to look at something like TreeMap if you need the order to stay the same between calls.
having said that, chances are that code will print out the same thing twice, it's just not guaranteed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With