Why to override equals() method?
To compare two object references either “==” or “equals” method, inherited from class Object, are used. The == operator evaluates to true only when both the references refer to the same object. This is because == only looks at the bits in the variables. So to find out if two references are meaningfully equal then equals() method has to be used. Since String class and the wrapper classes have overridden the equals() method, we could compare the two different objects to see if their contents are meaningfully equivalent.
For example-
Integer i= new Integer(200); Integer j= new Integer(200); if(i==j) System.out.println("i==j"); if(i.equals(j)) System.out.println("i meaningfully equivalent to j");
Output-
i meaningfully equivalent to j
Suppose we have the below code
public class test{ public static void main(String[] a){ t obj1=new t(1); t obj2=new t(1); if(obj1.equals(obj2)) System.out.println("obj1 meaningfully equivalent to obj2"); else System.out.println("obj1 not equal to obj2"); } } class t { int i; public t(int i){ this.i=i; } }
Output-
obj1 not equal to obj2
This is because class t didn’t override the equals() method inherited from the Object class and so the default behavior of the equals() method runs giving the above output. Since equals() method in class Object uses the == operator for comparison. So the two objects are considered equal only if their references point to the same object. Now to make the comparison meaningful, we have to override the equals() method in the t class in the following way.
class t { int i; public t(int i){ this.i=i; } public boolean equals(Object o){ if((o instanceof t)&&(((t)o).i==this.i)) return true; else return false; } }
Output-
obj1 meaningfully equivalent to obj2
Now in overridden equals() method in the t class, we are comparing to see if both references have the same i value or not. If they have the same i value then we return true to indicate that both the references are meaningfully equal and false if they are not. The important things to take care when overriding the equals method is that
1) The method takes a parameter of type Object and not the type of the class that is overriding the method.
2) It is a good practice to first check if the passed object is an instance of the class that is overriding since you might end up in a situation where two objects of different class types might be considered equal.
So when we need to know if two references are identical, we use==. But when we need to know if the objects themselves(not references)are equal,then use equals() method. If you don’t override the class’s equal method, you won’t be able to use those objects as a key in a Map, since while retrieving the value we need to compare the objects and you probably won’t get accurate Sets, such that there are no conceptual duplicates for which we need to compare to find out.