CuriousMind
CuriousMind

Reputation: 15808

Java Mutable Object as Map Key but using default hashCode()

I understand using immutable object as map keys are preferable. But how about mutable objects with default hashCode() method (and of course, I don't override the equals() method). That should also be fine, since default hashCode() uses the object memory address?

Is there anything I miss here?

Upvotes: 1

Views: 749

Answers (3)

Vaibhav Jain
Vaibhav Jain

Reputation: 187

Mutuable Objects as a Key with default equals() and hashcode() is of no use..

e.g

map.put(new Object() , "value") ;

when you want to get that value ,

map.get(new Object()) ; // This will always return null

Because with new Object() - new hashcode will be generated and it will not point to the expected bucket number on which value is saved, and if eventually bucket number comes to be same - it won't be able to match hashcode and even equals so it always return NULL

Upvotes: 0

cat916
cat916

Reputation: 1361

Below is hash code with string. However, an issue to worry about is the possible change of implementation between early/late versions of Java of string hash code.

public int hashCode()
{
    return "name".hashCode();
} 

In addition, there is an article hash collision probabilities

Upvotes: 0

Tim B
Tim B

Reputation: 41188

So long as the hashCode and equals method always return the same result it is safe to use the object as the key in the HashMap.

However you are probably reducing their utility as a key by doing so! The whole point of equals/hashCode is to identify equality between object values, and if you modify the members of an object is it really equal to how it was before the modification?

Upvotes: 4

Related Questions