Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Dec 16, 1998

What is an Object's Hash Code?

Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:
 
int hashCode = SomeObject.hashCode();
The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:
 
1.   // Compare objects and then compare their hash codes
2.   if (object1.equals(object2)
3.     System.out.println("hash code 1 = " + object1.hashCode() +
4.                        ", hashcode 2 = " + object2.hashCode());
5. 
6.   // Compare hash codes and then compare objects
7.   if (object1.hashCode() == object2.hashCode())
8.   {
9.     if (object1.equals(object2))
10.    System.out.println"object1 equals object2");
11.  else
12.       System.out.println"object1 does not equal object2");
13.   }
In lines 3-4, the value of the two hash codes will always be the same. However, the program may go through line 10 or line 12 in the code. Just because an object's reference equals another object's reference (remember that the equals() method compares object references by default), it does not necessarily mean that the hash codes also match.

The hashCode() method may be overridden by subclasses. Overriding the hash code will allow you to associate your own hash key with the object.

Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date