This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Problem with ContainsKey(obj key) in HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem with ContainsKey(obj key) in HashMap" Watch "Problem with ContainsKey(obj key) in HashMap" New topic

Problem with ContainsKey(obj key) in HashMap

Suhas Rao

Joined: Sep 06, 2004
Posts: 2
Hi ranchers,
well the issue is that i have got a class Emp{}
with some variables.
Now say i have 10 objects of this class and when 2 keys say EmpNo.&Deptno
is given i have to retrieve that objects properties.
Since i had to use two variables as keys
i thought of using HashMap where an object is used to map another object

i.e map.put(object Key,object value)
values=emp1,emp2 ....

but i had a problem while searching through the table.

Please help me out.
My code is

Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

but i had a problem while searching through the table

I could try to guess what this problem was. Far easier though would be if you told us - perhaps by listing an exception stacktrace or describing what went wrong?

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

For an object to serve as the key in a HashMap, it has to have correct hashCode() and equals() methods; the ones inherited from Object aren't good enough. Without these methods, two copies of a key with the same fields won't appear to be the same, so you won't be able to use the second copy to look up the object that was stored with the first copy. You haven't supplied these methods in Employee, and that explains the behavior you're seeing.

Implementing these methods can be tricky. Here's one of many references available to help you.

[Jess in Action][AskingGoodQuestions]
Jean Chastain

Joined: Oct 26, 2004
Posts: 7
Having used this post as my starting point, I overloaded hashCode in my key class and containsKey still didn't work. After much thrashing, I realized that I had (in the C++ canonical style to which I am accustomed) defined my equals method to take an argument of myKeyObject instead of Object. Since I had written my equals method before I read these threads (thanks, Ernest and others for patiently answering the recurring questions about hashMaps), I kept looking at it and seeing it matching the signature in the examples, which of course, it didn't.

Just posting it here for future reference.
I agree. Here's the link:
subject: Problem with ContainsKey(obj key) in HashMap
jQuery in Action, 3rd edition