dac2009
dac2009

Reputation: 3561

How is Java String hashCode calculated on objects

"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?

Upvotes: 0

Views: 227

Answers (1)

resueman
resueman

Reputation: 10623

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.

Upvotes: 4

Related Questions