COMPARING TWO OBJECTS IN JAVA
OVERRIDING EQUALS
METHOD
public class CompareData
{
private String param1;
private String param2;
public CompareData(String firstName,
String lastName)
{
this.param1 = firstName;
this.param2 = lastName;
}
@Override
public boolean equals(Object obj)
{
boolean isEqual = false;
if (this.getClass() == obj.getClass())
{
System.out.println("Entered for equality check..");
CompareData comp = (CompareData) obj;
if ((comp.param1).equals(this.param1) &&
(comp.param2).equals(this.param2))
{
isEqual = true;
}
}
return isEqual;
}
public static void main(String[] args)
{
CompareData obj1=new CompareData("Ram","Sita");
CompareData obj2=new CompareData("Ram","Sita");
if(obj1.equals(obj2))
{
System.out.println("Both the objects are equal");
}
else
{
System.out.println("Both the objects are not equal");
}
}
}
No comments:
Post a Comment