0

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!

Dan Temple
  • 2,736
  • 2
  • 22
  • 39
Daniel
  • 35
  • 7

2 Answers2

1

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.

Kakarot
  • 4,252
  • 2
  • 16
  • 18
0

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))))
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • `public boolean equals(Object p){` `if(p==null)` `return false;` `if(this.getAge()==p.getAge() && this.getName().equals(p.getName()))` `return true;` ` return false; }` I don't know how to write this method with Object as parameter so I cand override... – Daniel May 14 '14 at 15:57
  • A quick search shows [this post](http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk). you're missing a cast in your `equals` implementation. (after which you can use it). – Jeroen Vannevel May 14 '14 at 15:59