My Set
sometimes sorted, and sometimes not.
Here is an example:
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); } }
The result shows that Set
not sorted.
8 5 13 11 1 29 28 20 12 7 [1, 20, 5, 7, 8, 11, 12, 29, 28, 13]
When I change the termination expression to i < 20
in for a statement, the result shows that Set
become sorted.
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]
This is so weird, isn't it? I just don’t know how to explain this, and I need help, thanks a lot.