Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem getting value from HashMap

 
Paul McKenna
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 6529
21
Java Linux Mac Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gopi Balaji
Ranch Hand
Posts: 84
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic