Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Maps : what role does hashCode() play while inserting in a map?  RSS feed

 
mani manisha
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per the SCJP book:



The answer is:
1) As the code stands the output will be 3
2)Add a note here If the hashCode() method is uncommented the output will be 2


I have tried this .. and its right..
But did not quite understand why it is so..
i know duplicate keys not allowed.. but need to understand what role does hashCode() play while 'inserting' in the map?
And also the code works without the hashCode() function... then what hachCode criteria (if it DOES contribute in decision of inserting an element or not )was used in this case?


Thanks in advance...

Ok.. rephrasing my question...
Without the hashCode() function, the code inserted THREE elements in the map.. Even though the Keys are same(equals on the keys t1 and t2 returns true)...
and when you uncomment the hashCode(), the code inserts only TWO elements... Please explain why?

Continue.. i printed the map (m) running the code with the bad hashCode() function on.. .. so the map now contains
{ToDos@9=cleanAttic, ToDos@9=payBills}
As per my understanding it should have been 2 elements 1) cleanAttic 2) doLaundry... why did it insert payBills instead of doLaundry(assuming it HAD to insert only One of the two as both had same keys)?
 
Campbell Ritchie
Marshal
Posts: 55741
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is a very poorly designed hashCode method. The idea is that a HashMap takes the hash code to decide which "bucket" to put the pair of references in. If you always return 9, everything will go into bucket 9 regardless, and the performance of the Map will be very poor. Other Maps might work differently, but most Java™ Maps use the hash code like that.
 
Campbell Ritchie
Marshal
Posts: 55741
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That equals() method won't work properly; if you pass anything other than a Todos, you will suffer a ClassCastException. Also, you can get incorrect results if you use == to compare Objects.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!