简体   繁体   中英

Java Map hash code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM