File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in K&B SCJP 5: Using Maps 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 "Doubt in K&B SCJP 5: Using Maps" Watch "Doubt in K&B SCJP 5: Using Maps" New topic
Author

Doubt in K&B SCJP 5: Using Maps

Marcin Skrzek
Ranch Hand

Joined: Oct 19, 2005
Posts: 38
There is a misleading (in my opinion) example code on page 563:



I claim that, because of the way in which equals() method is overriden for Dog class (Dog`s member variable - name - is String, so shouldn`t it be compared to another variable using equals() instead of ==, should it?)

The side effect is, that if we slightly change code on page 565 from:


which gives the output: "Dog key"

to:


than the output will be: null

and we have now String constant pool issue in chapter about Collections, what isn`t even mentioned, but we read later (page 566, line 6):


In the second call to get(), the hashcodes are both 6, so step 1 succeeds. Once in the correct bucket (the "length of name = 6" bucket), the equals() method is invoked, and since Dog's equals() method compares names, equals() succeeds, and the output is Dog key.



Bert, sorry, if my tone seems to be to impertinent. My intention was only to clearly explain my doubt.

Thanks


SCJP 5, SCWCD 1.4, SCBCD 5
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi all,

I think, Marcin is right, the comparison should be made with equals. Personally I like to override equals with what I call the this-and-that-method:



Yours,
Bu.


all events occur in real time
Marcin Skrzek
Ranch Hand

Joined: Oct 19, 2005
Posts: 38
Bu,

Maybe I`m wrong, but your method:



seems to throw NullPointerException on runtime, when this.name is null.

Cheers,
Marcin
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi Marcin,

yes, all members of reference type to be compared should be checked that they are not null before they are compared. Unless the rest of the class doesn't provide that they can never be null (which is not the case in the Dog class).

Yours
Bu.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in K&B SCJP 5: Using Maps