"==" compares whether the two objects are same instances or not. It will return true if the two objects under comparison refers to the same instance in the JVM.
While the default implementation of "equals()" method which resides in the class Object is implemented such that it checks both the state i.e the contents of the objects under comparison as well as the reference to the object the objects refers to (same as "==" does). So the default implementation of "equals()" method will return true only if the states are same as well as reference to the JVM are also same.
Many examples in the web gives the example to compare two String objects as
s1 = new String("abc");
s2 = new String("abc");
if(s1==s2)
System.out.printlln("s1==s2 is TRUE");
else
System.out.println("s1==s2 is FALSE");
will print False.
while
if(s1.equals(s2))
System.out.println("s1.equals(s2) is TRUE");
else
System.out.println("s1.equals(s2) is FALSE");
will print true.
IMPORTANT THING TO KEEP IN MIND HERE IS, if s1 and s2 are custom objects instead of String, then s1.equals(s2) will not return true.For example: I define a custom object as
public class TestObject {
private String name;
private int id;
public TestObject(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
s1 = new TestObject("xxx", 1);
s2 = new TestObject("xxx", 1);
Now to make "equals()" method to return true for matching contents you need to override the "equals()" method.
s1.equals(s2) WORKS FOR STRING, BECAUSE STRING OVERRIDES THE equals() METHOD TO COMPARE THE CONTENTS OF TWO STRINGS. [SEE HERE FOR SOME GOOD EXPLANATIONS]
So to see s1.equals(s2) true for our custom object, our custom class TestObject should also define a method equals as:
public class TestObject {
.....
.....
@Override
public boolean equals(Object obj){
if (obj == null)
return false;
if (obj == this)
return true;
if (obj.getClass() != getClass())
return false;
TestObject rhs = (TestObject) obj;
if ( rhs.getId() != getId()){
return false;
}
if ( rhs.getName() != getName()){
return false;
}
return true;
}
}
System.out.println(obj1 == obj2) will print False
While
System.out.println(obj1.equals(obj2)); will print True
However, when you override equals() method you also need to override hashcode() method. See HERE for details.
No comments:
Post a Comment