• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Book p583/ Generics and Collections / HashMap Sample code

 
Vicky Wang
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

The following code:


In the book, it's stated because Cat class does not overwrite hashCode() and equals(), Cat instance cannot be found.
However, when I tried keeping the reference to the cat obj, I get the "Cat key" output for the line above.

Can someone explain this?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34074
337
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because you are using the same cat object when doing the get.

If you try this way instead, it should return null:


The same physical object (c1) returns the same has code so you get luck y and the Cat gets returned. In my example, it is a different Cat object as key and the luck is gone.
 
Vicky Wang
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then I would assume the following code should be able to find Dog:



but the output is null.

Why is that?
 
Ankit Gareta
Ranch Hand
Posts: 67
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vicky Wang wrote: then I would assume the following code should be able to find Dog:



but the output is null.

Why is that?


Hi Vicky, that should not be null if you correctly override equals and hashCode method..
 
Himai Minh
Ranch Hand
Posts: 1228
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vicky Wang wrote: then I would assume the following code should be able to find Dog:



but the output is null.

Why is that?


d1 has its unique hashcode in this example. For instance, the hashcode is 12345678.
The new Dog ("Charlie") has its own unique hashcode as well.
For instance this new dog object has hashcode = 87654321.

When the get method is called, it looks for hashcode 87654321 in the map, m . But there is no 87654321 hashcode in m. That was why it returns null.
 
Vicky Wang
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit Gareta wrote:
Vicky Wang wrote: then I would assume the following code should be able to find Dog:



but the output is null.

Why is that?


Hi Vicky, that should not be null if you correctly override equals and hashCode method..


I rewrote the same code on my linux machine and it found "Charlie" just fine.
Need to go back to my Mac and recheck code.
In any case, thanks for the reply!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic