【发布时间】:2018-12-10 10:24:10
【问题描述】:
我写了以下代码,
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};
然后在最后一行输出中,控制台显示,
num_set: [1, 2, 3, 100, 4, 200]
我想知道为什么在添加操作之后之前的顺序被改变了。
【问题讨论】:
-
使用考虑排序的
TreeSet。在HashSet中,检索时不考虑添加顺序,List会这样做。如果您使用的是自定义类(您定义的类),那么您必须将您的类设为Comparable或Comparator类型。 -
如果您希望对
Set的整数进行排序,请使用SortedSet。将您的行Set<Integer> num_set = new HashSet<Integer>();更改为类似 `SortedSetnumSet = new TreeSet ();