Domanda What is the purpose of the Java hashCode() method?

urooj

Utente Iron
20 Dicembre 2022
9
5
0
9
I attended an interview and was asked this question.

There are two objects with the same hashcode. I am inserting these two objects inside a hashmap.

Codice:
hMap.put(a,a);
 hMap.put(b,b);

where a.hashCode()==b.hashCode()

Now tell me how many objects will be there inside the hashmap?

I answered there will be only one object since the hashcodes are equal the two objects will be equal and hashmap will not allow duplicate keys. Please tell me whether my understanding is correct or not?
 
Nope, the hashcode is used to put objects in different buckets of the hashmap.

Different objects can have the same hashcode, but still having different keys. Therefore, there will be two objects in the hashmap.

The fact that objects with the same key must have the same hashcode, doesn't imply that different objects must have different hashcode
 
  • Mi piace
Reazioni: JunkCoder