aspose file tools*
The moose likes Beginning Java and the fly likes containsKey() question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "containsKey() question" Watch "containsKey() question" New topic
Author

containsKey() question

Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
Given



and this



I expected to get true in both cases. Why does the second call to containsKey() return false?


Costs matter. Justice lies in processes not outcomes. Crime is caused by criminals.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19073
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
Got it, thank you!
Evelin Priyadarsini
Greenhorn

Joined: Jun 19, 2008
Posts: 5
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

Joined: Oct 27, 2005
Posts: 19791
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: containsKey() question