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:
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.equals
method, then their hashes should be equal too.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.
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.
hashCode
function by making use of @Override
. This will ensure that the user-defined value is displayed.equals
function in a similar manner. In the function compare the attributes that you want to be similar.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 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