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

The purpose of HashCode

 
Paul Yule
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Yule
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's quite right. You can do clever-er things too; hash tables let you skip the vast majority of comparisons altogether.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic