Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help needed in understanding the hashCode() method

 
Rajshekhar Paul
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hiya Ranchers,

I was going through the chapter 7 in SCJP 6 K&B book.
However, I have some doubts regarding the hashCode() method.

As per my understanding, hashcodes are used prominently in collection classes like HashMap etc, hashcodes are used to perform search operations in such classes.
The book says that if I override equals() method in a class, I need to override the hashCode() method too!
I have modified the code snippet in page 552 of that book as the below one.

So, if I create two separate instances of the class HasHash both having same x value, they are said to be meaningfully equal according to the overridden equals() method.
But regardless of the instances, all of them will have same hashcode 1234. Now, how these two instances are going to behave if I put them in a HashMap which holds the HasHash object as the key and some string as the value?
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well the hashCode method is used to put objects in their correct buckets. In you code the hashCode method will return the same hashCode for all the objects. So all of them will go into the same bucket. But since the equals method is also overridden, so two instances HashHash having same value for x will be considered equal. So if you add two instances of HashHash (having different value for x) as key into a HashMap, then they will go into the same bucket but they will be unequal according to the equals method so they can both be added to the HashMap. But if you add two instances of HashHash with the same value for x, then they will both again go into the same bucket and since they are meaningfully equal, so the second add operation will replace the value of the first operation.

And also to clarify, if you would have not overridden the hashCode method in your class, then the objects would go into separate buckets and thus more than one objects which are meaningfully equal could be added to a HashMap...
 
Rajshekhar Paul
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit, for the reply. It was a good help!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic