• Post Reply Bookmark Topic Watch Topic
  • New Topic

java hashcode  RSS feed

 
Emanuel Mensa
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i got this from wikipedia but i don't really understand it. can someone please explain this to me? and the REAL use of the hashCode...:
In the Java programming language, every class must provide a hashCode() method which digests the data stored in an instance of the class into a single hash value (a 32-bit signed integer). This hash is used by other code when storing or manipulating the instance - the values are intended to be evenly distributed for varied inputs in order to use in clustering.


 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short version is that a hashCode is a "summary" of an object's state (contents) that, while not unique, will be different for different states as much as possible, which serves to reduce the number of items we have to look through one by one to find what we're searching for. Imagine hundreds or thousands of employee folders. If they were all just in one big pile, it would take you a long time to find any particular one, but if they're in file cabinets with drawers labeled with the first letter of the Employees last name, that lets you immediately jump to a much smaller pool to search through.


For more details, see http://en.wikipedia.org/wiki/Hashcode, or do your own Google search.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Emanuel Mensa wrote:i got this from wikipedia but i don't really understand it. can someone please explain this to me? and the REAL use of the hashCode...

I think Jeff's explained it pretty well, but there's quite a lot to know about hashes (and also digests and checksums, which are similar, but not the same), so I suggest you do some reading.

What you're seeing in terms of code is a fairly typical method for producing a "compound hash" from numeric values that make up a class, and based on the idea of 'bit shuffling'; but it's by no means the only one.

Winston
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that article is a bit imprecise in saying, “must provide”; since hashCode() is implemented in the Object class, every class “does provide” a hash code implementation. You can get away without overriding it if you are not putting instances of your class in hash‑based collections.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!