如何在 HashSet 中保留插入顺序? [英] How can I preserve insertion order in a HashSet?

查看:72
本文介绍了如何在 HashSet 中保留插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的代码,

public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
    num_set.add(num);
    System.out.println("num_set: " + num_set.toString());
}

然后我有测试用例,

int[] nums  = {100, 4, 200, 1, 3, 2};

然后在最后一行输出中,控制台显示,

then in the last line output, the console shows,

num_set: [1, 2, 3, 100, 4, 200]

我想知道为什么在添加操作后更改了之前的顺序.

I'm wondering why the previous order was changed after the add operation.

推荐答案

声明 HashSet 文档

没有保证集合的迭代顺序;特别是,它不保证订单会保持不变随着时间的推移.

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.

如果您想使用保持自然顺序的 Set,请使用 SortedSet 代替.

If you want to use a Set that remains natural order, use a SortedSet instead.

进一步提供其元素的总排序的集合.元素使用它们的自然顺序进行排序,或者通过通常在排序集创建时提供的 Comparator 进行排序.

A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time.

Set 的定义是不说明其元素的顺序.例如,如果两个 Set 包含相同的元素并且具有相同的大小,则它们是相等的.Set 的迭代顺序取决于实现并且可能会在版本之间发生变化,因此您不应对其进行任何假设.它可能取决于 #hashCode 的值,但也可能取决于未来的插入顺序或其他东西.但是,我们不应该在意,因为如果您这样做,您应该使用 ListSortedSet 来代替.

A Set does by definiton not say anything about the order of its elements. For exmaple, two Sets are equals if both contain the same elements and have the same size. The iteration order of a Set is dependent on the implementations and may change between versions, so you should not make any assumptions on it. It may depend on the value of #hashCode, but it may as well depend on the insertion order or something else in the future. However, we should not care, because if you do you should use a List or a SortedSet instead.

这篇关于如何在 HashSet 中保留插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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