This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using classes as Keys in Map problem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator






why isn't it returing null as ToDos class doesnot override equals or hashCode ?

K&B book Sorting Collections and Arrays page-583
Remember that when you use a class that implements Map, any classes that you
use as a part of the keys for that map must override the hashCode() and equals()
methods. (Well, you only have to override them if you're interested in retrieving
stuff from your Map. Seriously, it's legal to use a class that doesn't override equals()
and hashCode() as a key in a Map; your code will compile and run, you just won't
find your stuff.
)
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta wrote:
why isn't it returing null as ToDos class doesnot override equals or hashCode ?

Because you're using the same object to retrieve it. That's always going to work. What overriding hashCode and equals allows you to do is use a different object of the same value to retrieve things (which is often what you want).

Try this:
Now you'll get null.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta, what is the use of your Map? If you gave the exact object which is used as the key, then only you can retrieve the value object. Otherwise, you can't retrieve the object. Is this the situation you want? If so, you don't need to override those methods. What will you do, if you have a situation as Matthew Brown said?
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks,i got it now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic