aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help needed in understanding the hashCode() method 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 "Help needed in understanding the hashCode() method" Watch "Help needed in understanding the hashCode() method" New topic
Author

Help needed in understanding the hashCode() method

Rajshekhar Paul
Ranch Hand

Joined: Oct 17, 2006
Posts: 140
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?


When it's obvious that you have to do it, just do it without shattering your thoughts over different directions.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rajshekhar Paul
Ranch Hand

Joined: Oct 17, 2006
Posts: 140
Thanks Ankit, for the reply. It was a good help!
 
 
subject: Help needed in understanding the hashCode() method