aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hash code question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hash code question" Watch "hash code question" New topic
Author

hash code question

warren li
Ranch Hand

Joined: May 23, 2006
Posts: 128
Hi,

this is taken from the SCJP 5 book, Page626, Qn 7:



As the code stands, I understand it outputs "3".

But I don't understand why hashCode() is uncommented, it outputs "2"?

Based on "THIS LINE" of code, t1.equals(t2) should be false, because it is comparing their "day" using "==", not "equals()". Then based on this logic, t2's value should not replace t1's. then there will be 3 mappings in the map.
Where is my understanding wrong? Thanks.


SCBCD 1.3: 94%<br />SCWCD 1.4: 91%<br />SCJP 5: 95%
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
1)

ToDos t1 = new ToDos("Monday");
ToDos t2 = new ToDos("Monday");

"t1.day == t2.day" is true. Both reference point to the same string object.

2)
uncomment public int hashCode() { return 9; };
The equals() function will be called by each time when you add any elements into the hashmap. Thus, t2's value will replace t1's value.
warren li
Ranch Hand

Joined: May 23, 2006
Posts: 128
So the first time "Monday" is created on the string pool, the second time Monday is simply referenced from the same Monday. is it this way?
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Yes. You are right.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hash code question