Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value.
If you look into the source code of Object class you will find the following code for the equals() method.
public boolean equals(Object obj) {
return (this == obj);
}
Here is an example of how hashCode() and equals() works: The Emp class, at first, we only override the hashCode() method:
public class Emp {
private int age;
public Emp(int age) {
super();
this.age = age;
}
// variable age is the significant factor
public int hashCode() {
return age;
}
}
In the test, we'll see that even though we override the hashCode() method, the result of emp1.equals(emp2) is "false":
public static void main(String[] agrs) {
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(23);
System.out.println("emp1.hashCode()--->>>"+emp1.hashCode()); //emp1.hashCode()--->>>23
System.out.println("emp2.hashCode()--->>>"+emp2.hashCode()); //emp2.hashCode()--->>>23
System.out.println(emp1.equals(emp2)); // false
}
Then let's override the equals() method as well:
public class Emp {
private int age;
public Emp(int age) {
super();
this.age = age;
}
// variable age is the significant factor
public int hashCode() {
return age;
}
public boolean equals(Object obj) {
boolean flag = false;
Emp emp = (Emp) obj;
if (emp.age == age) {
flag = true;
}
return flag;
}
}
The test:
public static void main(String[] agrs) {
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(23);
System.out.println("emp1.hashCode()--->>>"+emp1.hashCode()); //emp1.hashCode()--->>>23
System.out.println("emp2.hashCode()--->>>"+emp2.hashCode()); //emp2.hashCode()--->>>23
System.out.println(emp1.equals(emp2)); //true
}
So, here are Three rules that are good to know about implementing the hashCode() method in classes:
If object1 and object2 are equal according to their equals() method, they must also have the same hash code. If object1 and object2 have the same hash code, they do NOT have to be equal too. And also, if you are going to override the one of the methods( ie equals() and hashCode() ) , you have to override the both otherwise it is a violation of contract made for equals() and hashCode().
No comments:
Post a Comment