Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the class HashSet<T> has values already sorted when I use the iterator?

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
like image 296
Sddf Avatar asked Jan 13 '15 19:01

Sddf


1 Answers

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.

like image 102
Sotirios Delimanolis Avatar answered Sep 28 '22 18:09

Sotirios Delimanolis