This week's book giveaway is in the Beginning Java forum.
We're giving away four copies of Murach's Java Programming and have Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with ContainsKey(obj key) in HashMap  RSS feed

 
Suhas Rao
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
key(empno,deptno)
values=emp1,emp2 ....

but i had a problem while searching through the table.

Please help me out.
My code is

 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jean Chastain
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!