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

查看:449
本文介绍了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天全站免登陆