况且HashSet并不关心key的“排序”,就算其iterator“有序”通常也是说“按元素插入顺序”(LinkedHashSet就支持插入顺序遍历)。题主在此看到的所谓“有序”纯粹是个巧合。
public class Test {
public static void main(String[] args){
Random rand=new Random(47);
Set<Integer> intset=new HashSet<Integer>();
Set<Integer> intset1=new TreeSet<Integer>();
for (int i=0;i<10000;i++){
intset.add(rand.nextInt(30) + (1 << 16));
intset1.add(rand.nextInt(30) + (1 << 16));
}
Iterator<Integer> iterator=intset.iterator();
Iterator<Integer> iterator1=intset1.iterator();
while (iterator.hasNext()){
System.out.print((iterator.next() - (1 << 16)) +" ");
}
System.out.println();
while (iterator1.hasNext()){
System.out.print((iterator1.next() - (1 << 16)) +" ");
}
}
}
HashSet输出:
16 17 18 19 20 21 22 23 24 25 26 27 28 29 1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14
TreeSet输出:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29