File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Problem getting value from HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem getting value from HashMap" Watch "Problem getting value from HashMap" New topic

Problem getting value from HashMap

Paul McKenna

Joined: Jan 17, 2003
Posts: 8
I have the following code

The above code for some reason isnt able to get the value back from the HashMap. I printed out the whole HashMap and I can see that it contains the said key and value. I have also implmented the equals method in the MyKey class but for some reason it is never called (I checked that by putting a println statement in the equals method)
Can anyone find the bug?
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

You said you overrode the equals method; did you remember to override the hashCode() method as well? I think HashMap checks hashCode() first, which it uses to put values in "buckets", then checks keys in the bucket for equality. If you didn't override hashCode() and assuming MyKey is a direct subclass of Object, then the key you used with put() will have a different hashCode() value from the key you use with get() and you won't get to the point where equals() gets called.

Junilu - [How to Ask Questions] [How to Answer Questions]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
You probably need to implement the hashCode() method in MyKey. In general you should always override hashCode() whenever you override equals(), and vice versa. Effective Java by Joshua Bloch has a good short section on making hashcode() and equals() methods.

"I'm not back." - Bill Harding, Twister
Gopi Balaji
Ranch Hand

Joined: Jan 23, 2003
Posts: 84
Originally posted by Paul McKenna:
HashMap m = new HashMap();
MyKey key = new MyKey(MyConstants.PRIMARY_KEY); // MyKey is just a wrapper class around a string constant
m.put(key, "Nothing here");
System.out.println("Value for mykey : "+key);// use the already defined key

Perhaps this might work, if Object.hashcode() is not overridden.
Paul McKenna

Joined: Jan 17, 2003
Posts: 8
Thank you! I had to override the hashCode method. It worked once that was done
I agree. Here's the link:
subject: Problem getting value from HashMap
jQuery in Action, 3rd edition