为什么set<Integer>是排序加值?

Why set <Integer> is sorting added values?

当我开始向 Set<Integer> 添加值时,我得到了排序元素。 请参考这个例子:

Set<Integer> generated = new HashSet<Integer>();
generated.add(2);
generated.add(1);
generated.add(0);

这里我得到排序Set[0, 1, 2]。我想在添加到 generated 对象时获得价值。

A​​ HashSet 没有可预测的元素顺序。使用 LinkedHashSet 保留集合中元素的插入顺序:

Hash table and linked list implementation of the Set interface, with predictable iteration order.

Set<Integer> generated = new LinkedHashSet<Integer>();
generated.add(2);
generated.add(1);
generated.add(0);

首先,您第一次获得排序值只是巧合。如果您多次 运行 该代码,您将看到以某种随机顺序排列的输出。那是因为 HashSet 不会强制对您添加的元素进行任何排序。

现在要按照您插入的顺序获取元素,您可以使用 LinkedHashSet,维护插入顺序。

HashSet 不保证元素的顺序。来自 JavaDoc:

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.

所以,为了保证顺序可以使用LinkedHashSet。来自 JavaDoc:

Hash table and linked list implementation of the Set interface, with predictable iteration order.

This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

只需像这样实例化您的 Set

Set<Integer> generated = new LinkedHashSet<>();

首先,关于你的问题的标题,Set<Integer>只是声明类型,它不对任何排序/取消排序行为负责,这是使用的主要原因Set 接口是在关心唯一性时——它不允许重复,来自 Javadocs:

的附加信息

A Set is a Collection that cannot contain duplicate elements.

其次, 完全有信心你得到了排序集,当你在遍历它时不关心顺序时使用 HashSet,更多信息来自 javadocs:

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. This class permits the null element.

第三,关于你要找的东西:

I would like to get value as I add to generated object.

然后您需要使用 LinkedHashSet 来处理元素插入的顺序,再次来自 javadocs:

This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set

您可以像这样简单地使用它:

Set<Integer> generated = new LinkedHashSet<Integer>();

第四个和最后一个,作为附加信息,您需要注意的另一个重要 collection 是 TreeSet,它保证元素将按照自然顺序升序排列,javadocs:

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used