Wednesday, 29 January 2014

Overriding equals() method

We mostly touch with equals method when doing String operations. We do compare two String objects with equals method, this equals method performs equality based on data instead of reference.

Like String class, Object class has equals method. But this equals method performs equality based on reference instead of data.

So, equals method performs equality in two ways

  1. Logical Equality
  2. Reference Equality
Logical Equality
          String s1 = new String("StabbingCode");
          String s2 = new String("StabbingCode");
          s1.equals(s2)  // it returns true. because here equals performs logical equality

Reference Equality
          Lets take a class Horse
          Horse horse1 = new Horse("White");
          Horse horse2 = new Horse("Brown");
          horse1.equals(horse2) // it returns false, because here equals performs reference equality.

So, In this cases we should override Object's equals method and make a logic for perform equallity based on data.
           Now, I did override equals method like following

public class Horse{
String color;
public Horse(String color)
{
this.color = color;
}

public static void main(String[] args) {
Horse obj1 = new Horse ("White");
Horse obj2 = new Horse ("White");

System.out.println(obj1.equals(obj2));
}

@Override
public boolean equals(Object obj) {
if(null == obj)
return false; // sometimes object may refer to null, for avoiding NullPointerException
if(this.getClass() != obj.getClass()) //both objects should be instance of same class
return false;
if( !this.color.equals(((Horse )obj).color) )
return false;
                return true;
}
}


       

No comments:

Post a Comment

Followers