Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map hash code

Tags:

java

hashcode

map

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 ?

like image 291
javaq Avatar asked Dec 21 '22 20:12

javaq


2 Answers

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.

like image 110
John Gardner Avatar answered Dec 24 '22 11:12

John Gardner


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).

like image 31
Laurence Gonsalves Avatar answered Dec 24 '22 10:12

Laurence Gonsalves