The whole purpose of using containsKey() is to check whether any given key is already in HashMap or not? If it doesn't contain that key than just add key into that HasMap.

But seems like when we call this method it's parameters are Object
type that means, containsKey() checks whether given argument(key) has
similar memory address with any other already entered key.

Potential Solution:

One solution could be get a unique data from that object1(oldKey) and
check with object2(new key), If they are same than don't use it in
HashMap. However this means containsKey has no purpose at all. Am I
right?

Sorry I am not ranting, or probably I sound like one. But I would like to know the most efficient way to get over this problem.

Your question doesn't really make much sense at the moment. What problem are you talking about, what are you trying to achieve, where does "If not than don't add it" come from?
–
Jon SkeetSep 14 '11 at 13:04

4 Answers
4

But seems like when we call this method it's parameters are Object type that means, containsKey() checks whether given argument(key) has similar memory address with any other already entered key.

Wrong. Their equality is checked by comparing their hashCode() values first. Only if the hash values are equal, the objects themselves may be compared (but always using equals(), not ==). So any class where these two methods are implemented properly will work correctly as a key in a HashMap.

HashMap.containsKey() methods finds if whether the key's hashCode() exists and not by equality comparison. If the hash code exists, it will pull the entry to see if the reference equality OR equals() of the key is equal.

But seems like when we call this method it's parameters are Object type that means, containsKey() checks whether given argument(key) has similar memory address with any other already entered key

This conclusion is wrong. The containskey(Object key) calls the equals() method on the passed key , so if this has overriden the equals(Object key) method , then it will resolve correctly based on the key equivalence criteria. Ofcourse if the Key has not overridden the equals() method , then it is a bad design to start with.