Java – why are the values of class HashSet sorted when I use iterators?

I have the following code on the main method. When I traverse set and print the value, the value has been 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

Solution

It was just a coincidence A HashSet does not reserve or guarantee any order

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>