Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is map/collection order stable between calls?

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.

like image 383
John Avatar asked Dec 06 '22 02:12

John


2 Answers

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.

like image 97
Michael Borgwardt Avatar answered Dec 15 '22 01:12

Michael Borgwardt


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.

like image 35
chris Avatar answered Dec 15 '22 01:12

chris