• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in K&B SCJP 5: Using Maps

 
Marcin Skrzek
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Marcin Skrzek
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic