• Post Reply Bookmark Topic Watch Topic
  • New Topic

HashMap  RSS feed

 
k reeta
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am really confused about how HashMaps work. According to the code below, two instances of Dog are equal if they share the same name, and the hashcode has been overridden as well.



My question is - when I try to use d3 as a key, why do I get null as the value?? Since d3.equals(d2) returns true , and their hashcode are equal -shouldn't the value for d3 be "Dog2" (like it is for d2)?

What am I doing/understanding wrong?

Thank You.
 
Sanjeev Ba
Ranch Hand
Posts: 40
Android Chrome Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
d3.equals(d2) returns true due to the overridden equals() method. This is not related to the HashMap.

s.get(d3) depends on the HashMap implementation. HashMap "s" does not have a key called "d3" (which will be a reference to some object).
So, it does not know which "value" you want to retrieve. It doesn't know how to resolve "d3" key to get you a value.

I guess that explains why you are getting a null.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, Sanjeev, that's not correct. Read the API for HashMap.get(...)

reeta, Java is case sensitive. Add the @Override annotation to your overridden methods in the Dog class and you'll spot your mistake in no time.
 
Sanjeev Ba
Ranch Hand
Posts: 40
Android Chrome Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice Gotcha..Thanks for pointing out.
 
k reeta
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for pointing me in the direction! I changed hashcode to hashCode and its working now. Thank you!
 
sakthi moorthy
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Darryl Burke wrote:Sorry, Sanjeev, that's not correct. Read the API for HashMap.get(...)

d3 Object is not added to the HashMap Object "s" That's why "null" is getting printed as Sanjeev Says.

Please Correct me if i am wrong or where i went wrong.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!