Guide to hashCode() in Java

May 09, 2022
Xblog HashCode


Hashing is a very significant concept in the field of computer science. It is the process of mapping the data to a unique integer value using one of the hashing algorithms. It enables relatively quick access to the objects as compared to other access methods.

Hashing can be implemented through a function called hashCode() in Java.

A hash code is an integer value in Java that is linked with every object.  In Java, there are some very efficient hashing algorithms such as the HashMap and the HashSet.

In this article, we will be mainly focusing on how to use the hashCode() method. We will be discussing its working and how it is implemented correctly.

new java job roles

Use of Java hashcode() Method

The Java hashCode() is used for bucketing in Hash implementations such as HashMap, HashTable or HashSet.

The value returned from the hashCode() is then used as a bucket number for storing the elements/ values of the set/map. This bucket number is the address of the element inside the set/map.

Understanding hash code

A hash code is a number generated by the Java hashcode() method. This integer value allows objects to be stored/retrieved quickly from a HashMap. To understand it better, consider the following simple example.

Suppose, you have 10 containers, each marked with a number 1 to 10. You also have a collection of random items to be stored in these containers.

You need to select a specific container for each item so that you could also retrieve that item as quickly as possible.

To be able to immediately find out which item is present in which container, you can use a simple algorithm.

You can decide the container with the number of letters in the name of the item.

This way, the ball goes in container 4, the pin will then go into container 3, the puppet in container 6, the chain in container 5 and so on.

Following this algorithm, a single container can most likely end up with more than one item in it.

It will still be a way quicker approach to compare a few items inside a single container than comparing it with all the items in each container.

That is the concept of hash code, an algorithm generates a number from an object so it can be easily stored and then can also be quickly retrieved from a HashMap.

Types of Java hashCode () method

There are primarily 2 types of Java hashCode() method based on their respective parameters:

1. hashCode() Method

The Java hashCode method with no parameters belongs to the Java Integer class.

The syntax is as follows:

public int hashCode ()

This method returns the hashcode of the current object which is equal to the int value.

2. hashCode(int value) Method

This hashCode(int value) method has a single parameter which is of integer data type. It determines the hashcode of the given integer parameter (value).

Its syntax is shown below:

public static int hashCode(int value)

This method returns the hashcode for the integer “value” that is passed to the method.

Implementation of hashCode in Java

The following code is a simple implementation of a Java hashcode generating a hashcode for a string:

1.  import*;
2.  public class JavaClass {
4.    public static void main(String args[]) {
6.      String myStr = new String("How to implement Java hashcode");
7.      System.out.println("Hashcode for the string :" + myStr.hashCode() );
8.   }
9.  }

equals() method

The equals() method offers to compare whether the two objects are equal or not. This method is provided by the Object class in Java.

The equals() method is commonly used in hashMaps to compare the keys to whether they are equal or not. If they are equal, the method returns true otherwise false.

Following is an implementation of the Java hashcode() method used to generate hashcode, first for two equal objects and then for two unequal objects.

The equals() method is then used to check whether the objects are equal or not.

1.  import*;
2.  public class JavaClass {
4.     public static void main(String args[]) {
5.       String str1 = "abc";
6.       String str2 = "abc";
7.       if(str1.equals(str2))
8.     {
9.      System.out.println("both variables are equal.");
10.     System.out.println(str.hashCode() + "n" + str2.hashCode());
11.    } 
12.    String str3 = "abcd";
13.    String str4 = "efgh";
15.    if(!str3.equals(str4))
16.    {
17.       System.out.println("Variables are unqual");
18.       System.out.println(str3.hashCode() + "n" + str4.hashCode());
19.    }
20.  }
21. }

Upon output, the hashcode of str1 and str2 will be the same as both the variables are equal whereas str3 and str4 will have different hashcode as they are not the same.

Now, this code implementation shows how to retrieve a hashcode in Java by passing a parameter to the Java hashcode() method.

1.   public class hashcode_with_Parameters { 
2.      public static void main(String[] args) 
3.      { 
4.          int hash_code = Integer.hashCode(25); 
5.          System.out.println("Hash code Value for the object : " +hash_code); 
6.      } 
7. }

Using Java hashCode() with HashMap

Java hashCode() function returns a hashcode value of the passed object. It returns an integer that is generated by a hashing algorithm.

A hashing algorithm maps the unique keys with their respective values. The values are then stored in the calculated memory locations using the hash data structures.

One such data structure is HashMap. These values then can be quickly retrieved using their keys for various operations.

Index Calculation using Java hashCode

A Hash code of key can be very large sometimes. It can be large enough to require an array to be stored.

The generated hash code can consist of a wide range of integers. If arrays are created of such a huge range, it will eventually result in an outOfMemoryException while storing them.

To avoid that, the Java hashcode method is used to generate an index key to keep the size of the array to a minimum.

The following operation is used to calculate index values for the Java hashmap:

index = hashCode(key) & (n-1).

Here, n is the size of the array also called the number of buckets.

Advantages of using the Java hashCode() method

HashCode() in Java allows a program to run significantly faster. For instance, a comparison method such as equals() takes almost 20 times more time in searching an object as compared to using the hashcode() method.

Also Read: Java Compiler Error: “class, interface, or enum expected”

Thanks to hash data structures the elements are properly organized in an array-based data structure which makes it easier to locate an object.


In this article, we have explored the importance of the Java hashCode() method along with equals(Object) to efficiently store and retrieve data using a hash table.

There is furthermore to be discovered such as the use of the hashcode() method with other data structures.

When working with the hashCode method in Java, you must keep in mind to generate different hash values for unequal objects while using a hashing algorithm.

The Java hashCode() method should also be very consistent in its implementation of the equals() function.

new Java jobs



Candidate signup

Create a free profile and find your next great opportunity.


Employer signup

Sign up and find a perfect match for your team.


How it works

Xperti vets skilled professionals with its unique talent-matching process.


Join our community

Connect and engage with technology enthusiasts.