遍历 HashSet class 的实例,期望随机顺序但结果总是相同的顺序

iterating through instance of HashSet class, expect random order but the results are always the same order

我正在尝试在 java 中学习 Set 接口和 HashSet class 的概念。我已阅读

when using HashSet class, that there is no guarantee of the sequence of elements when I iterate over.

我想出了一些代码 运行 十次,它总是按插入顺序迭代。那么这是运气吗?

Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);

Iterator i1 = set1.iterator();
while (i1.hasNext()){
    System.out.println(i1.next());
}

根据 javadoc:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. [...] The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created

Java4我们有LinkedHashSet保证迭代顺序和插入顺序相同。

是的。这是由于 "luck"。这取决于 JRE 实现!多年前,我在 Java 中开始实施时 艰难地学习了这一点 ,并且代码在 不同的平台 .

如果我记得,在 windows 中 HashSet 迭代是完美有序的,但在 Mac OSX 中完全混乱!

底线:始终依赖文档,而不是表面结果!