*
The moose likes Beginning Java and the fly likes The purpose of HashCode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "The purpose of HashCode" Watch "The purpose of HashCode" New topic
Author

The purpose of HashCode

Paul Yule
Ranch Hand

Joined: May 12, 2008
Posts: 229
I'm a little hazy as to the need of an objects hashcode. It is my understanding that hashcode is a generated number of sorts that identifies a particular Class.

So if you were to ever compare an instance of Class A with another Instance of Class A their hash codes would be the same. Their equals() may or may not be true and their "==" evaluation will be false.

It is also my understanding (which is limited at best) that hash codes are not unique to any particular Class and Class B may or may not have the same hashcode as Class A. What would be the purpose of the hashcode then?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi Paul,

Substitute "object" for "class" above. The hashCode() method returns a semi-unique value for each object. As such, it's about as useful as a person's name (for example.) It's not absolutely guaranteed to be unique, just as there are many "John Smith"s in the world, but it usually is unique for a given small set of objects. Hashcodes are often used as a way to sort objects into piles for faster lookup, to do a very fast "probably equal" computation before doing something more complicated, or to identify objects during debugging.


[Jess in Action][AskingGoodQuestions]
Paul Yule
Ranch Hand

Joined: May 12, 2008
Posts: 229
OK, thanks.

Allow me to see if I understand. It's primary reason is for performance. There is a huge set of data and we are searching for specific values. Let's suppose we need to do an equals() on all of it and an equals method may take a while to compute especially for complex objects. By using hashcode to begin with we can eliminate quite a few of the possibilities at the onset rather than towards the end of the equals() evaluation; Thus improving performance.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Yes, that's quite right. You can do clever-er things too; hash tables let you skip the vast majority of comparisons altogether.
 
GeeCON Prague 2014
 
subject: The purpose of HashCode