Map.keySet和Map.values的迭代顺序相同吗? [英] Same iteration order on Map.keySet and Map.values?

查看:114
本文介绍了Map.keySet和Map.values的迭代顺序相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于像这样的地图:

Map<Integer, Integer> map = ...;
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);

这是代码...

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?

如果没有,例如<​​code> java.util.HashMap 有保证吗?

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).

如果要保证迭代顺序,请迭代 entrySet()

If you want to guarantee iteration order, iterate the entrySet():

for (Map.Entry<Integer,Integer> entry : map.entrySet())
    // ...

由于您询问有关 HashMap 的信息,因此请注意重新映射后,地图可能会更改迭代顺序。

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.

这篇关于Map.keySet和Map.values的迭代顺序相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆