Search code examples
javadictionaryequalshashcodemultikey

Java: Map with doubleKey type, how to make the right hashCode()?


I have a MultiKey object as keys for a Map.

A Key consists of a Name (String) and an ID (int).

The following contract has to be fullfilled: Keys have to be equal if either the names of both keys are equal or the ids of both keys.

How do I have to implement the hashCode() function so that this contract is not violated? Is it even possible?

Implementing equals is easy... i just put:

if (name.equals(other.name) || id == other.id)
    return true;

But this won't work because hashMap only uses hashCode() and does not care about equals()...

Example:

Map A = [ ("tom",1)=TOMAS, ("eli",2)=ELIAS ]

A.get(new Key("tom",0))    should return TOMAS
A.get(new Key("",1))       should return TOMAS
A.get(new Key("eli",2))    should return ELIAS
...

Solution

  • About the only way I can see to do this would be to build a set to TreeSet to cache the hashCodes for the keys. Then use the first equals value encountered as the hashCode value for the current execution. Problems with this:
    a. Can use a lot of extra memory if there are many distinct keys.
    b. The hashCode values will not necessarily be consistent across multiple executions of the program.
    c. If multi-threaded, synchronization will be required against the cached hashCodes.

    If you do this, the hashCode could simply be generated combining name and id like you always would.