• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

containsKey() question

 
Thomas Kennedy
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given



and this



I expected to get true in both cases. Why does the second call to containsKey() return false?
 
Henry Wong
author
Marshal
Pie
Posts: 21431
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I expected to get true in both cases. Why does the second call to containsKey() return false?


A HashMap, Hashtable, HashSet, etc... basically, all the hashing collections, depends on both the equals() and hashCode() method to determine equality. You forgot to override the hashCode() method.

Henry
 
Thomas Kennedy
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it, thank you!
 
Evelin Priyadarsini
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Kennedy:
[QB]Given



Hi,
i have a doubt, whether instance of Klingon k will be equal to the new instance created i.e(new Klingon(5))
Because the new instance created will reference a different memory right. Can you please clear this one.

Thanks in Advance.
[ June 24, 2008: Message edited by: Evelin Priyadarsini ]
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Evelin Priyadarsini:

i have a doubt, whether instance of Klingon k will be equal to the new instance created i.e(new Klingon(5))
Because the new instance created will reference a different memory right. Can you please clear this one.

Equality is determined by the "public boolean equals(Object)" method. As Thomas has specified in this method that two Klingon objects are equal if their rank is equal, and both have a rank of 5, the objects should be equal.

Of course, if you override equals, you should also override the "public int hashCode()" method, as it is specified in the API for java.lang.Object. And that's exactly what Thomas forgot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic