Before looking at equals method in java first we we will take a look at what equals method does. equals method is the method of Root class of hierarchy Object class. This method basically compares one object with another object for equality. This method checks some of the properties indicated below:
It checks object equality to itself. i.e. for any reference value obj, obj1.equals( obj ) should return true.
Symmetric property is checked by checking object in both the ways like
obj1.equals( obj2 ) is returned as true only when this condition obj2.equals( obj1 ) == true gets satisfied.
Suppose there are three objects then if obj1.equals( obj2 ) and obj2.equals( obj3 ) both are true then obj1.equals( obj3 ) must return true.
obj1.equals( obj2 ) should Consistently return either true or false obviously provided object information is not modified in between.
Null Value check :
For object like obj1 which is not null, obj1.equals( null ) should always return false.
Also if obj1.equals( obj2 ) returns true then hashcode of the two objects must be same and if it returns as false then there hashcodes may be same or different.
So if we want to override the equals method in our object let see how we should approach for writing our own equals method :
1. this test .
If object passed is this itself then we dont need to check the things further, so at the very beginning we can add this check such as
if( obj1 == this )
2. null check.
if object passed is null then also we dont ned to check the things further, so we can add check for null also like
if( obj1 == null )
3. getClass check for type identification :
We can use getClass method to check if two classes are same or not.
if (obj.getClass() != this.getClass()))
if your class is immutable, then we can use instanceof method . The reason behind not using the instanceof method is if returns true for subclasses also .
4. Type cast the object
We need to type cast the object to compare the fields , but type casting should be always after the getClass or instanceof check.
5. Comparing Fields
We need to compare the fields according to their type , for object fields we can use equals method, for Array fields we can use Arrays.equals method, for primitive fields other than float and double we can use == , for float and double we can convert them to int and long respectively and then use ==. for type safe enumerations we can use == or equals.
While comparing it is always better to compare primitive fields such as int first as it takes less time than other checks, also we need to make sure that field which we are comparing is not null.