Buszman Buszman - 9 days ago 6
Java Question

Why HashSet is sorted?

I am learning about containers in Java and I've read recently that HashSet doesn't give the elements in order. What's interesting for Integer my randomly made HashSet is sorted. When I changed its type to Double the printed HashSet was sorted no more. My question is: does HashSet work differently for various types then?

Answer

HashSet uses a HashMap internally. HashMap stores its elements in a hash table using each Object's hashCode() method.

For int and double, these are auto-boxed into the Integer and Double classes. When you make a HashSet of ints, it uses Integer's hashCode() method, which just returns the int. So if you add ints, they get stored sorted. But for double, Double's hashCode() method is much more complicated, because of the way doubles are represented in memory.