0

"Sun" and "TWO" gives the same hashCode() values in Java.

How come this outputs:

HashMap<String, Integer> map = new HashMap<>();
map.put("Sun", 1);
System.out.println(map.get("TWO"));

outputs: null

but

HashMap<Integer, Integer> map = new HashMap<>();
map.put("Sun".hashCode(), 1);
System.out.println(map.get("TWO".hashCode()));

outputs: 1

Isnt hashmap calling hashCode() on the string "Sun" to use it as a key?

1 Answer 1

4

When an object is inserted into a HashMap, it does use the hashCode method to decide where to store it. But hashCodes aren't intended to be completely unique. There can be different values that produce the same output but aren't equal, so the HashMap will have some method of dealing with collisions like that. get will only return a value if the keys have both the same hashCode, and are equal using the equals method. "Sun" does not equal "TWO", but the hashCode of "Sun" does equal the hashCode of "TWO".

From the documentation:

if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

So it's equality, not the hashcode, that determines what gets returned. The hashcode is effectively just an optimization to make the process of finding which objects are likely to be equal much faster.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.