aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using classes as Keys in Map problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using classes as Keys in Map problem" Watch "Using classes as Keys in Map problem" New topic
Author

Using classes as Keys in Map problem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634







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.
)

OCPJP 6.0 93%
OCPJWCD 5.0 98%
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

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

Joined: Nov 04, 2009
Posts: 2066

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?


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

thanks,i got it now
 
wood burning stoves
 
subject: Using classes as Keys in Map problem