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?
Asked
Active
Viewed 4,768 times
4
-
1It depends on the hash codes. – SLaks Nov 29 '16 at 15:52
-
Do not rely on the order of a hashset. Anything you find is purely coincidental by dint of whatever code & hashing function is implemented under the hood. – CollinD Nov 29 '16 at 15:52
-
@CollinD I just made a for loop and put 10 000 elements in the HashSet using random.nextInt(); – shurrok Nov 29 '16 at 15:55
-
I'm sorry, I don't understand how that is related to what I said. – CollinD Nov 29 '16 at 15:56
-
I mean, i don't understand why hashing function works differently for Integer and Double? – shurrok Nov 29 '16 at 15:58
-
The docs for `HashSet` indicates it is backed by a `HashMap`. The entire public contract of the `HashMap` can be read at https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html – CollinD Nov 29 '16 at 16:01
2 Answers
7
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 int
s, it uses Integer's hashCode() method, which just returns the int
. So if you add int
s, they get stored sorted. But for double
, Double's hashCode() method is much more complicated, because of the way doubles are represented in memory.

Adam Millerchip
- 20,844
- 5
- 51
- 74
1
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