Same iteration order on Map.keySet and Map.values?

谁说胖子不能爱 提交于 2019-12-22 03:35:10

问题


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?


回答1:


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

for (Map.Entry<Integer,Integer> entry : map.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.




回答2:


No, not guaranteed. One is Set and one is Collection, neither guarantee the order.

If you would like to keep order. May be LinkedHashMap() with entrySet() help you.




回答3:


Yes. Sort of. You can use a subclass of SortedMap, i.e. TreeMap. That will keep keys in a natural order. (or you can give it a specific comparator). But when you use tree map, you HAVE to make sure the compareTo method "must be consistent with equals". Read the javadocs for more details. But in short, yes, you CAN sort a map.



来源:https://stackoverflow.com/questions/12286986/same-iteration-order-on-map-keyset-and-map-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!