Francisco Spaeth
Francisco Spaeth

Reputation: 23903

Java Map Implementation not based on HashCode

Is there some implementation of java.util.Map that does not uses HashCode?

I have the following problem:

  1. I store an object associated to another object on a HashMap;
  2. Change a property from the key object used on step 1;
  3. As the hashcode is used to store the keys on the regular implementation of HashMap, when I perform a get() on the HashMap, I get null, because the old object hashCode was different at step 1.

Is there a solution for that? Or should I really use just immutable fields for my equals / hashCode methods?

Upvotes: 11

Views: 4257

Answers (7)

Mark Rotteveel
Mark Rotteveel

Reputation: 108961

IdentityHashMap uses the Object identity instead of the hashCode; however that does mean that you require the original object used as key to retrieve the value of the map. Other options would be redefine the hashcode to exclude the mutable parts of the object, or - if you can't redefine the hashCode for some reason - wrap the object in another object which provides a stable hashCode.

Upvotes: 16

All associative containers use comparing or hash code, so I would like to recommend you using immutable fields for equals() / hashCode() methods.

Upvotes: 1

Zava
Zava

Reputation: 763

I think modify the key object in map is not a good practice.

But if you really want, you can override the hashCode() and remember to override the equal() method.

Upvotes: 1

duffymo
duffymo

Reputation: 308743

All Maps should use immutable objects for keys. True for Python; true for Java.

If you implement equals and hashCode using only immutable fields you should be fine.

Upvotes: 2

Tvd
Tvd

Reputation: 4601

How about removing and adding it again ?

On Step 2, You can remove the element added in Step 1 and again add it with new latest properties set. This way when you are try to get in Step 3, you will find it.

Try it.

Upvotes: 1

Azodious
Azodious

Reputation: 13872

Override equals and hashCode methods if you don't want original implementation.

Upvotes: 0

skaffman
skaffman

Reputation: 403451

You would be well advised to use an immutable key, and to re-insert the key/value pair into Map, rather than mutating the key in-place. As you discovered, that just leads to weird bugs.

If this isn't an option for you, then see if you can ignore the mutable property in the hashCode() method, so that the hash code doesn't change. If that's the only property of the class, though, that's not a good idea.

You may be able to get away with using TreeMap, which I don't think uses hashCode(). However, it does require consistency between the key's compareTo() and equals() methods, so you may just end up with the same problem as before if the return values of those methods can change.

Upvotes: 9

Related Questions