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?
HashSet uses a
HashMap stores its elements in a hash table using each Object's
double, these are auto-boxed into the
Double classes. When you make a
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.