Friday, September 11, 2009

Overriding the equals and hashCode methods

Override the equals method when you want to specify the rules of logical equality of objects.
If these methods are not override then :
Person p1 = new Person("Binod",26);
Person p2 = new Person("Binod",26);
p1.equals(p2) -> Will return FALSE. But logically both object are same. Because equals method in Object class only check the references of object NOT containts.

So make the logical equals, Use override equals methods in Person class.

public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
Person person = (Person)obj;
return age == person.getAge() && name.equals(person.getName());

}
After adding this method in Person class then
Person p1 = new Person("Binod",26);
Person p2 = new Person("Binod",26);
p1.equals(p2) -> Will return TRUE.

Why override hashcode() method.
When use the hash based collection in your code then only equals method will not work. For example. Now as above code p1 and p2 are logically equal objects. So,

Set set = new HashSet();
set.add(p1);
set.add(p2);
System.out.println("Size of Set :: "+set.size()); Output would be 2, but it should be 1, as both objects are logically same and Set keeps unique data. So, we have to override the hashCode() method.
In Person class, add one more method.


public int hashCode() {
int hashCode = 0;
final int multiplier = 23;
if (hashCode == 0) {
int code = 133;
code = multiplier * code + age;
code = multiplier * code + name.hashCode();
hashCode = code;
}
return hashCode;
}

after compilation check
Set set = new HashSet();
set.add(p1);
set.add(p2);
System.out.println("Size of Set :: "+set.size()); Output would be 1.

During add the p1 object into Set, it will call hashCode() method of p1, now adding p2 object then again it will call hashCode() method of p2. If both hashcode values are equals then it will call object equals() method to final check, if it return true then set will not add second p2 object. If equals() method does not override then it will add second p2 object. If hashcode values are not equal then set would not be call equals() method.

No comments:

Post a Comment

Please put your feedback or your any question related to this blog. Thanks.