devxlogo

What is an Object’s Hash Code?

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 codes2.   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 objects7.   if (object1.hashCode() == object2.hashCode())8.   {9.     if (object1.equals(object2))10.    System.out.println"object1 equals object2");11.  else12.       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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist