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.