[英]Random Iteration order from Set.of(…)
Hi I am learning the new features of Java 9 and was reading new Collections API's.嗨,我正在学习 Java 9 的新功能,并且正在阅读新的 Collections API。 I am not sure why I am getting random iteration order while creating an immutable set from two instances of JDK.我不确定为什么在从 JDK 的两个实例创建不可变集时得到随机迭代顺序。
JDK 1: jshell> Set.of("a","b","c")
$96 ==> [a, b, c]
JDK2 : jshell> Set.of("a","b","c")
$68 ==> [a, c, b]
I don't see the same for List.of() overloads.Can I do some customisation like changing some system properties to guarantee a consistent ordering here?对于 List.of() 重载,我看不到相同的内容。我可以进行一些自定义,例如更改某些系统属性以保证此处的顺序一致吗?
Arbitrary Set
implementations have no ordering, so any iteration order encountered when iterating over the elements of a Set
returned by Set.of()
is correct, and you shouldn't rely on it.任意Set
实现没有排序,因此在迭代Set.of()
返回的Set
的元素时遇到的任何迭代顺序都是正确的,您不应该依赖它。 It's an implementation detail, and different JDK versions can produce different iteration orders.这是一个实现细节,不同的JDK版本可以产生不同的迭代顺序。
If you require a consistent ordering, either don't use Set
s, or use Set
s that guarantee order, such as TreeSet
.如果您需要一致的顺序,请不要使用Set
s,或者使用保证顺序的Set
s,例如TreeSet
。
List.of()
has a different behavior, since List
s have ordering. List.of()
具有不同的行为,因为List
具有排序。 In the List
returned by List.of("a","b","c")
, "a" will always be the first element, "b" the second element and "c" the third.在List.of("a","b","c")
返回的List
中,“a”始终是第一个元素,“b”是第二个元素,“c”是第三个元素。
As Eran already explained, the iteration order of a Set
is not specified.正如Eran已经解释的那样,没有指定Set
的迭代顺序。
To avoid that other programs rely on the iteration order, the JVM will create a salt at startup and use that to randomize the iteration order of their internal Set
and Map
implementations:为了避免其他程序依赖于迭代顺序,JVM 将在启动时创建一个 salt,并使用它来随机化其内部Set
和Map
实现的迭代顺序:
/** * A "salt" value used for randomizing iteration order. This is initialized once * and stays constant for the lifetime of the JVM. It need not be truly random, but * it needs to vary sufficiently from one run to the next so that iteration order * will vary between JVM runs. */ private static final long SALT32L;
In short: They did additional work to make the iteration order "random", so things will break if people start to rely on the order.简而言之:他们做了额外的工作来使迭代顺序“随机”,所以如果人们开始依赖这个顺序,事情就会中断。
And some programs do rely on the iteration order of HashSet
for example - which makes it hard to improve HashSet
now without breaking programs that rely on the order.例如,有些程序确实依赖于HashSet
的迭代顺序——这使得现在很难在不破坏依赖顺序的程序的情况下改进HashSet
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.