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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.