I have the following code on my main
method, and when I iterate through the Set
and print the values, the values are already sorted. What's the reason?
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);
}
Output:
2
3
6
7
9
That's just coincidence. A HashSet
does not preserve or guarantee any ordering.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With