For a map like:
Map<Integer, Integer> map = ...;
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
Is this code…
for (Integer i : map.keySet()) System.out.println(i);
for (Integer i : map.values()) System.out.println(i);
…guaranteed print the same same sequence twice?
If not, are there any guarantees in for example java.util.HashMap?
No, there is no guarantee, although in practice it will happen (there’s no good reason for the map to use a different iterator for the keys and values).
If you want to guarantee iteration order, iterate the
entrySet():Since you ask about
HashMap, note also that any changes to the map will potentially change iteration order, as a result of the mapbeing rehashed.