aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem getting value from HashMap" Watch "Problem getting value from HashMap" New topic
Author

Problem getting value from HashMap

Paul McKenna
Greenhorn

Joined: Jan 17, 2003
Posts: 8
Hi..
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?
Thanks
PMc
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4419
    
    5

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
Wanderer
Sheriff

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.
-GB.
Paul McKenna
Greenhorn

Joined: Jan 17, 2003
Posts: 8
Yep!
Thank you! I had to override the hashCode method. It worked once that was done
PMc
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem getting value from HashMap
 
Similar Threads
Key in the HashMap.
equals() & hashCode()
can you please this doubt about hashcode()
Use Case where hashCode() is required & not equals()
maximum Integer value problem with HashMap(String, Integer)?