What is the hashCode method in Java?

svg viewer

The hashCode method is an inbuilt method that returns the integer hashed value of the input value.

Here are a few key concepts to remember:

  • Multiple invocations of the hashCode must return the same integer value within the execution of a program unless the Object used within the equals method changes. The integer value need not be the same for the next implementation.
  • If two or more objects are equal according to the equals method, then their hashes should be equal too.
  • If two or more objects are not equal according to the equals method, then their hashes can be equal or unequal.

Remember: If you override the equals method, it is crucial to override the hash method as well.

Code

The following code shows how to declare a hashCode:

public int hashCode()
{
//your hash function here
}
svg viewer

For a user-defined hashCode function, the following steps are followed, but not necessarily in this order.

  • Make a base class that contains attributes for the objects that the user defines.
  • Override the predefined hashCode function by making use of @Override. This will ensure that the user-defined value is displayed.
  • Override the predefined equals function in a similar manner. In the function compare the attributes that you want to be similar.
  • In the main function, declare objects of the base class and make use of the hashCode and equals functions to ensure that the objects are equal.

The following code suggests one of the ways that a user-defined hashCode method can be implemented to compare two objects.

//declare a class
public class Password{
//declare attributes
private String password;
private String retypedpassword;
//setters and getters
Password(String x){
this.password = x;
}
public String getpassword()
{
return this.password;
}
//Override the predefined hashCode function
@Override
public int hashCode(){
return (int) password.hashCode();
}
//Override the predefined equals function
@Override
public boolean equals(Object x){
if (x == null)
return false;
Password y = (Password) x;
return y.getpassword() == this.getpassword() ;
}
}
//declare a separate class to compare two objects
class hashes{
public static void main(String args[])
{
//declare two objects
Password p1 = new Password("ABC");
Password p2 = new Password("ABC");
//compare and print
System.out.println("Hash for password 1: ");
System.out.println(p1.hashCode());
System.out.println("Hash for password 2: ");
System.out.println(p2.hashCode());
System.out.println("Equal? ");
System.out.println(p1.equals(p2));
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved