Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with ContainsKey(obj key) in HashMap

 
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
Marshal
Pie
Posts: 24212
35
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic