Java HashSet 中元素的排序
为什么第二组和第三组保持顺序:
Integer[] j = new Integer[]{3,4,5,6,7,8,9};
LinkedHashSet<Integer> i = new LinkedHashSet<Integer>();
Collections.addAll(i,j);
System.out.println(i);
HashSet<Integer> hi = new HashSet<Integer>(i);
System.out.println(hi);
LinkedHashSet<Integer> o = new LinkedHashSet<Integer>(hi);
System.out.println(o);
这是我得到的输出:
3,4,5,6,7,8,9
3,4,5,6,7,8,9
3,4,5,6,7,8,9
Why do the second and third sets preserve order:
Integer[] j = new Integer[]{3,4,5,6,7,8,9};
LinkedHashSet<Integer> i = new LinkedHashSet<Integer>();
Collections.addAll(i,j);
System.out.println(i);
HashSet<Integer> hi = new HashSet<Integer>(i);
System.out.println(hi);
LinkedHashSet<Integer> o = new LinkedHashSet<Integer>(hi);
System.out.println(o);
Here's the output I get:
3,4,5,6,7,8,9
3,4,5,6,7,8,9
3,4,5,6,7,8,9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二个(仅使用
HashSet
)只是一个巧合。来自 JavaDocs:第三个 (
LinkedHashSet
) 是 设计是这样的:The second one (just using
HashSet
) is only a coincidence. From the JavaDocs:The third one (
LinkedHashSet
) is designed to be like that:@Behrang的答案很好,但更具体地说,
HashSet
似乎与LinkedHashSet
顺序相同的唯一原因是integer.hashCode( )
恰好是整数值本身,因此数字恰好在HashSet
内部存储中按顺序排列。这是高度特定于实现的,正如@Behrang所说,这确实是一个巧合。例如,如果您使用
new HashSet<>(4)
将存储桶的初始数量设置为 4(而不是 16),那么您可能会得到以下输出: value >= 16,你可能会得到这样的结果:
@Behrang's answer is good but to be more specific, the only reason why the
HashSet
seems to be in the same order as theLinkedHashSet
is thatinteger.hashCode()
happens to be the integer value itself so the numbers happen to be in order in theHashSet
internal storage. This is highly implementation specific and as @Behrang says, really a coincidence.For example, if you use
new HashSet<>(4)
which sets the initial number of buckets to be 4 (instead of 16) then you might have gotten the following output:If you had stuck in values >= 16, you might get something like this: