Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hash code question

 
warren li
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. You are right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic