• Post Reply Bookmark Topic Watch Topic
  • New Topic

What does hashCode() method really mean?  RSS feed

 
Ratan Kumar Yadav
Greenhorn
Posts: 6
Flex Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can Somebody help regarding hashCode() method of Object class.What is its importance?
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do you know what is hashing technique? have a look at hash based collection like java.util.HashMap
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The hashCode() method returns a number that is a kind of identifier for the object, but it isn't necessarily a unique identifier.

Hash-based collection classes (such as HashMap and HashSet) use this to organize the objects that they contain in such a way that they can quickly look objects up.

For example, look at HashSet. You can imagine a HashSet as a collection of buckets. Each bucket can contain one or more objects, and each bucket has a label. Let's make it even more concrete for the example. Suppose you have a HashSet with 10 buckets. When you put an object in the HashSet, it will look at the last digit of the hash code of the object and put the object in that bucket. So, if the hash code ends with 0, it will go into bucket 0; if it ends with 1, in bucket 1, etc. By doing it that way, the HashSet distributes all the objects that you put into over its 10 buckets.

Now, suppose that you want to check if an object is present in the HashSet. You call contains(someObject) on the HashSet. The HashSet now looks at the hash code of someObject, and immediately knows in which of the 10 buckets to look. It can skip the other 9 buckets, which saves a lot of work. It only has to call equals() on the objects that are in one of the buckets.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!