Which is the best way to compute the hash code of a Map
, knowing that it may contain entry values of types such as: String
, Integer
, Object[]
... ?
Map.hashCode()
returns a shallow hash code. That means that if you have a String[]
in your map, the Map.hashCode()
will also use the hash returned by the String[]
. Which, unfortunately, is not what I want (the Object.hashCode()
implementation). But I want the Arrays.hashCode(String[])
implementation.
So which is the best, generic, approach to handle this ?
If you need to know if two maps contain the same values, you will need to write a deep comparison method. you shouldn't be depending on hashCode.
even with a perfect algorithm, there's no way that every possible collection of every possible object could be uniquely represented by a single signed integer.
Hashcode is just for collision reduction when used in collections, it is not supposed to be used to uniquely identify objects.
The solution to your problem is to not use arrays. Use ArrayLists (or some other form of List, like an ImmutableList from Google's Guava). Lists hash the way you want. Also, arrays don't really play nice with generics (like Maps).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With