Java HashMap keySet() 迭代顺序是否一致? [英] is the Java HashMap keySet() iteration order consistent?

查看:23
本文介绍了Java HashMap keySet() 迭代顺序是否一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解从 Map 的 keySet() 方法返回的 Set 不保证任何特定顺序.

I understand that the Set returned from a Map's keySet() method does not guarantee any particular order.

我的问题是,它是否保证多次迭代的相同顺序.例如

My question is, does it guarantee the same order over multiple iterations. For example

Map<K,V> map = getMap();

for( K k : map.keySet() )
{
}

...

for( K k : map.keySet() )
{
}

在上面的代码中,假设地图没有被修改,那么对keySets的迭代是否会以相同的顺序进行.使用 Sun 的 jdk15 它确实以相同的顺序迭代,但在我依赖这种行为之前,我想知道是否所有 JDK 都会这样做.

In the above code, assuming that the map is not modified, will the iteration over the keySets be in the same order. Using Sun's jdk15 it does iterate in the same order, but before I depend on this behavior, I'd like to know if all JDKs will do the same.

编辑

我从答案中看到我不能依赖它.太糟糕了.我希望不必建立一些新的收藏来保证我的订购.我的代码需要迭代,执行一些逻辑,然后以相同的顺序再次迭代.我将从 keySet 创建一个新的 ArrayList 来保证顺序.

I see from the answers that I cannot depend on it. Too bad. I was hoping to get away with not having to build some new Collection to guarantee my ordering. My code needed to iterate through, do some logic, and then iterate through again with the same ordering. I'll just create a new ArrayList from the keySet which will guarantee order.

推荐答案

如果API文档中没有说明保证,那么你不应该依赖它.行为甚至可能会从一个版本的 JDK 更改为下一个版本,甚至来自同一供应商的 JDK.

If it is not stated to be guaranteed in the API documentation, then you shouldn't depend on it. The behavior might even change from one release of the JDK to the next, even from the same vendor's JDK.

你可以很容易地得到集合,然后自己排序,对吧?

You could easily get the set and then just sort it yourself, right?

这篇关于Java HashMap keySet() 迭代顺序是否一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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