HashSet 的迭代顺序 [英] Iteration order of HashSet

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

问题描述

如果添加到 java.util.HashSet 的每个对象都以确定性方式实现 Object.equals() 和 Object.hashCode(),则对于添加的每个相同元素集,HashSet 上的迭代顺序是否保证相同,不考虑它们的添加顺序?

If every object added to a java.util.HashSet implements Object.equals() and Object.hashCode() in a deterministic fashion, is the iteration order over the HashSet guaranteed to be identical for every identical set of elements added, irrespective of the order in which they were added?

额外问题:如果插入顺序也相同怎么办?

Bonus question: what if the insertion order is identical as well?

(假设 Sun JDK6 具有相同的 HashSet 初始化.)

(Assuming Sun JDK6 with same HashSet initialization.)

我最初的问题不清楚.它不是关于 HashSet 的一般契约,而是关于 Sun 在 JDK6 中的 HashSet 实现提供的关于确定性的保证.它本质上是不确定的吗?什么影响其迭代器使用的顺序?

My original question was not clear. It is not about the general contract of HashSet, but what Sun's implementation of HashSet in JDK6 offers as guarantees concerning determinism. Is it inherently non-deterministic? What influences the order used by its Iterator?

推荐答案

绝对不会.

每当发生桶碰撞时,插入顺序都会直​​接影响迭代顺序:

The insertion order directly influences the iteration order whenever you have a bucket collision:

当两个元素最终出现在同一个桶中时,第一个插入的元素也将是迭代过程中返回的第一个元素,至少如果碰撞处理和迭代的实现很简单(以及 Sun 的 java.util.HashMap 是)

When two elements end up in the same bucket, the first one that was inserted will also be the first one returned during iteration, at least if the implementation of collision handling and iteration is straightforward (and the one in Sun's java.util.HashMap is)

这篇关于HashSet 的迭代顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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