1

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?

1
  • 1
    If the only thing you rely on is the object's "address", then use an IdentityHashMap Commented Mar 18, 2014 at 15:55

3 Answers 3

4

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?

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

1 Comment

Hi Tim, I have a builder method that only builds the object with the same "name", for example. So there will always be the same object for a given identifier. What's mutable is only the content associated with the "name".
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.