0

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?

3
  • 1
    Are you sure A.equals(B) is true? Commented Jan 18, 2018 at 2:18
  • 1
    Why do you think it's "operating on key's hashCode only"? key gets passed to getNode, too, not just its hash code. Commented Jan 18, 2018 at 2:35
  • The overloaded equals method in String converts the given parameter into String, so you can't pass the character B directly to the equals method. Commented Jan 18, 2018 at 5:28

2 Answers 2

3

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).

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

Comments

1

why the contains could return false?

getNode may return null. It means that the node with the key is not found. The hash function is just hashing the key that is not available in the HashMap.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.