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 Generics (Using Maps) KB exam book page 583- 586 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 "Generics (Using Maps) KB exam book page 583- 586" Watch "Generics (Using Maps) KB exam book page 583- 586" New topic
Author

Generics (Using Maps) KB exam book page 583- 586

Peter Swiss
Greenhorn

Joined: Mar 03, 2011
Posts: 23

Here is the code from that page:




Thank you..
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

Peter when you add a key-value to a Map, the key-value is placed in a bucket based on the hash code. If after that you modify the key in such a way that it changes the hash code of the key, then your map gets sort of corrupt. The key-value is still in the Map but you will not be able to find it as its still in the old bucket in which it went when you added it...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Sergio Britos
Greenhorn

Joined: Oct 14, 2010
Posts: 4
Peter,

d1.name = "magnolia"; //Are we modifying the actual key in the map??? the key referenced by d1???
System.out.println(m.get(d1));

In this case you are modifying object d1 and when you invoke m.get (d1), Hashmap invoke hash method on d1 object and no bucket are found in HashMap. Then return null.

d1 not referts to the actual key in the map. When you pass d1 to get method, hashmap invoke your hascode() method at d1 and if bucket is found at hash table, then invoke your d1 equals method to find a match object (based on equals mehtod not the reference).
Peter Swiss
Greenhorn

Joined: Mar 03, 2011
Posts: 23
Thank you for your reply Ankit and Sergio... I will let you know if I have more questions.
fadi aboona
Ranch Hand

Joined: Apr 25, 2010
Posts: 71
Hi guys, i'm completely stuck trying to understand this:

if i change code line 65 above from:



To:



I get:

d1= Dog key

The equals method never got executed because i put but never got executed? how come? and why i'm not getting null instead of Dog key?

Thanks a lot.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics (Using Maps) KB exam book page 583- 586
 
Similar Threads
Doubt in collection
Maps
Issue in Working with Maps
working of map?
Bug in a kathy sierra prog...