Search code examples
javahashmaphashtablehashcode

hashCode() and key hash in HashMap


Assume String A = "c", Character B = 'c'.

I understand that A.hashCode() == B.hashCode() but A.equals(B) == false.

However, if you put A into a HashMap as a key. Then calling hashMap.contains(B) returns false although they have the same hashCode. Here's how Java implements some functions in HashMap.

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

As you can see HashMap is simply operating on key's hashCode() only. Then why the contains() could return false?


Solution

  • First A.equals(B) is false moreover String.equals(Object o) has this code

    if (anObject instanceof String) {
     //comparing strings
    } 
    return false;
    

    Also containsKey() calls getNode() which uses equals to distinguish between equal objects and objects with same hashCode (hash collisions).