What is the hashCode method in Java?
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
hashCodemust 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
equalsmethod, then their hashes should be equal too. - If two or more objects are not equal according to the
equalsmethod, then their hashes can be equal or unequal.
Remember: If you override the
equalsmethod, 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}
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
hashCodefunction by making use of@Override. This will ensure that the user-defined value is displayed. - Override the predefined
equalsfunction 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
hashCodeandequalsfunctions 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 classpublic class Password{//declare attributesprivate String password;private String retypedpassword;//setters and gettersPassword(String x){this.password = x;}public String getpassword(){return this.password;}//Override the predefined hashCode function@Overridepublic int hashCode(){return (int) password.hashCode();}//Override the predefined equals function@Overridepublic 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 objectsclass hashes{public static void main(String args[]){//declare two objectsPassword p1 = new Password("ABC");Password p2 = new Password("ABC");//compare and printSystem.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