Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why HashSet is sorted? [duplicate]

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?

like image 256
shurrok Avatar asked Oct 23 '25 16:10

shurrok


2 Answers

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.

like image 74
Adam Millerchip Avatar answered Oct 26 '25 06:10

Adam Millerchip


When hashing double, Java converts it to long since they both are simply 64-bit values in memory.

You can actually experiment the hashcode to see how it works for integer and double.

Check this for more details: Hash a double in Java

like image 22
Chen Chen Avatar answered Oct 26 '25 04:10

Chen Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!