import java.util.*;
public class DuplicateCheckMain {
public static void main(String[] gopal){
Integer[] args = {6,9,2,55,100,1,6,8,9};
Integer[] args1 = {3,6,2,3,5};
Set S = new HashSet();
DuplicateCheck.checkDuplicate(S,args,new String("HashSet"));
Set S1 = new HashSet();
DuplicateCheck.checkDuplicate(S1,args1,new String("HashSet"));
S = new TreeSet();
DuplicateCheck.checkDuplicate(S,args,new String("TreeSet"));
S = new LinkedHashSet();
DuplicateCheck.checkDuplicate(S,args,new String("LinkedHashSet"));
}
}
public class DuplicateCheck {
public static void checkDuplicate(Set S, Integer[] args, String setname){
for(int i = 0;i<args.length;i++){
if(!S.add(args[i])){System.out.println("Duplicate element "+args[i]);}
}
System.out.println(S +" "+ setname);
}
}
问题:对于引用S的HashSet,HashSet没有排序。但是对于引用 S1,HashSet 是排序的。为什么会这样?
最佳答案
HashSet
绝对不能保证排序。 根本无法保证顺序。
来自 iterator()
方法的文档:
Returns an iterator over the elements in this set. The elements are returned in no particular order.
HashSet
旨在通过相等性非常快速地插入和检查元素的存在。就这样。
如果您需要排序,您应该使用 SortedSet
的实现,例如 TreeSet
或 ConcurrentSkipListSet
。
关于java - HashSet 不保证排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4688493/