我在main方法上有以下代码,当我遍历Set并打印值时,值已经排序.什么原因?
Set<Integer> set = new HashSet<Integer>(); set.add(2); set.add(7); set.add(3); set.add(9); set.add(6); for(int i : set) { System.out.println(i); }
输出:
2 3 6 7 9
解决方法
那只是巧合. A
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.