我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);
}
}
Run Code Online (Sandbox Code Playgroud)
结果显示set未排序.
8 5 13 11 1 29 28 20 12 7
[1, 20, 5, 7, 8, 11, 12, 29, 28, 13]
Run Code Online (Sandbox Code Playgroud)
当我将终止表达式更改i < 20为for语句时,结果显示set变为已排序.
8 5 …Run Code Online (Sandbox Code Playgroud)