我的 Set
有时排序,有时不排序。
例子如下:
public class SetOfInteger {
public static void main(String[] args) {
Random rand = new Random(47);
Set<Integer> intset = new HashSet<>();
for (int i = 0; i < 10; i++) {
int j = rand.nextInt(30);
System.out.print(j + " ");
intset.add(j);
}
System.out.println();
System.out.println(intset);
}
}
结果显示 set
未排序。
8 5 13 11 1 29 28 20 12 7
[1, 20, 5, 7, 8, 11, 12, 29, 28, 13]
当我将终止表达式更改为 i < 20
时在for语句中,结果显示set
变得有序。
8 5 13 11 1 29 28 20 12 7 18 18 21 19 29 28 28 1 20 28
[1, 5, 7, 8, 11, 12, 13, 19, 18, 21, 20, 29, 28]
这很奇怪,是吗?我只是不知道如何解释它,我需要一些帮助,非常感谢。
最佳答案
HashSet 不保证迭代排序,但在非常特殊的情况下,其内部数据结构可能类似于 bucket sort。 .
具体来说,对于[0,65535]范围内的整数键和大于最大键的表大小,存储键的桶的索引等于键本身,并且由于迭代器迭代按桶顺序,它按排序顺序发出元素。
关于java - HashSet 是否在内部进行排序工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36236316/