Search code examples
javahashmapcollision

Can you explain this Java hash map key collision?


I have a HashMap and is used in the following way:

HashMap<SomeInterface, UniqueObject> m_map;

UniqueObject getUniqueObject(SomeInterface keyObject)
{
     if (m_map.containsKey(keyObject))
     {
         return m_map.get(keyObject);
     }
     else
     {
         return makeUniqueObjectFor(keyObject);
     }
}

My issue is that I'm seeing multiple objects of different classes matching the same key on m_map.containsKey(keyObject).

So here are my questions:

  1. Is this possible? The Map interface says it uses equals() to compare if the key is not null. I haven't overridden equals() in any of my SomeInterface classes. Does this mean the equals method can be wrong?

  2. If the above is true, how do I get HashMap to only return true on equals() if they are in fact the same object and not a copy? Is this possible by saying if (object1 == object2)? I was told early on in Java development that I should avoid doing that, but I never found out when it should be used.

Thanks in advance. :)


Solution

  • I strongly suspect you've misdiagnosed the issue. If you aren't overriding equals anywhere (and you're not subclassing anything else that overrides equals) then you should indeed have "identity" behaviour.

    I would be shocked to hear that this was not the case, to be honest.

    If you can product a short but complete program which demonstrates the problem, that would make it easier to look into - but for the moment, I'd definitely double-check your suspicions about seeing different objects being treated as equal keys.