Question

I have a problem with hashMap. More specific with containsKey. I want to check if a object exists in my hash. The problem is when I call this method with 2 different objects containing the same exact data, that should have same hashCode.

Person pers1,pers2;
pers1=new Person("EU",22);
pers2=new Person("EU",22);

public int hashCode(){ //From Person Class
    return this.getName().hashCode()+age;
}

After inserting the pers1 key in my hash and calling " hash.containsKey(pers1);" returns true but"hash.containsKey(pers2)" returns false. Why and how could I fix this issue?

Thank you!

Was it helpful?

Solution 2

containsKey() uses the .equals() method which you don't seem to override. .hashCode() provides a normalized (ideally) distribution across the hashtable, it does not do any equality comparisons (aside from requiring two equal objects require the same hashcode).

As you can see in the source code:

if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))

OTHER TIPS

The cause of the issue seems to be that you did not override the equals method in the Person class. Hashmap needs that to locate the key while searching.

The steps performed while searching the key are as follows :

1) use hashCode() on the object (key) to locate the appropriate bucket where the key can be placed.

2) Once bucket is located, try to find the particular Key using equals() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top