7

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 ?

7
  • 1
    I assume your Map is immutable? If your adding/removing entries, your values-based hashCode() is doomed. Commented Dec 10, 2010 at 17:37
  • I think most people's initial question will be "why?" what are you doing that you need to change the hashcode of the map? calculating a "deep" hashcode could make that operation pretty expensive... Commented Dec 10, 2010 at 17:37
  • 1
    @Kirk Woll: please detail, what's the point ? Commented Dec 10, 2010 at 17:40
  • @John Gardner: I need to know whether two maps hold the same values, in deep. In a generic manner. Commented Dec 10, 2010 at 17:42
  • 2
    @javaq, a hashCode will not guarantee that the two maps are equal anyway -- you're barking up the wrong tree. Two objects with different values may return the same hashCode(). If you want a deep equality comparison, you're just going to have to implement that yourself -- your own equals method. Commented Dec 10, 2010 at 17:47

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Do you know any other effective ways of achieving my goal ?
if you need to know that two collections are exactly the same, there's no real other way to do it other than a deep comparison. things that are not the same can fail quickly, but worst case is always comparing every inner object, including inner comparisons of every inner collection...
3

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

1 Comment

This is not a solution. I cannot control the input. Eventually I could recursively replace the arrays with array lists, but I would avoid that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.