Dudi
Dudi

Reputation: 2450

Java Arrays.hashcode() weird behaivor

I have an object which has one field- double[] _myField it's hashcode is

public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(_myField);
    return result;
}

However if I used the object as a key in a Map I get the following weird behavior:

for (Map.Entry<MyObject, String> entry: _myMap.entrySet())
    {
         if (entry.getValue() != _myMap.get(entry.getKey()))
         {
                 System.out.println("found the problem the value is null");

         }

    }

The only reason I can think of that the above IF statement is true is that I get a different hashcode for the key.

in fact, I have changed the hashcode function to return 1 in all cases. Not efficient, but good for debugging and indeed the IF statement is always false.

What's wrong with Arrays.hashcode()?

Pls note (after reading some comments): 1) As for the usage of != in the IF statement, indeed it compares references but in the above case it should have been the same. Anyhow the weird thing is that the right hand side returns NULL 2) As for posting Equals function. Of course I've implemented it. But it is irrelevant. Tracing the code in debug reveals that only hashcode is called. The reason for that is presumably the weird thing, the returned hashcode is different from the orignal one. In such cases the Map doesn't find a matching entry and therefore there is no need to call Equals.

Upvotes: 0

Views: 914

Answers (3)

Dudi
Dudi

Reputation: 2450

Trying to reproduce the problem on a clean slate revealed it is not reproducible.

Hence, further investigation revealed that the problem was the _myField used for Hash was changed while the object was stored in the map. As expected the map is corrupted.

Sorry for the time wasted by those who tried to answer the wrong question.

Upvotes: 0

anio
anio

Reputation: 9171

Implementing hashCode is not enough. You also need to implement equals object. In fact whenever you implement hashCode for an object, you MUST implement equals as well. Those 2 work together.

You need to implement equals for your object and ensure that whenever equals is true for 2 objects, their hashCode also matches.

Upvotes: 2

corsiKa
corsiKa

Reputation: 82589

Is the array being changed while it's in the map? Because that will change the outcome of the result.

Upvotes: 5

Related Questions