• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using classes as Keys in Map problem

 
Ranch Hand
Posts: 634
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
)
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks,i got it now
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic