equals() method

When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves (not the references) are equal, use the equals() method(which you may need to override).Comparing two object references using the == operator evaluates to true only when both references refer to the same object (because == simply looks at the bits in the variable, and they’re either identical or they’re not).
 
method signature of equals() method in Object class
public boolean equals(Object o)
 
The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object.
 
Overriding equals() method
class Moof 
{
private int moofValue;
Moof(int val) 
{
moofValue = val;
}
public int getMoofValue() 
{
return moofValue;
}
public boolean equals(Object o) 
{
if ((o instanceof Moof) && (((Moof)o).getMoofValue() == this.moofValue)) 
{
return true;
else 
{
return false;
}
}
}
public class EqualsExample 
{
public static void main (String [] args) 
{
Moof one = new Moof(8);
Moof two = new Moof(8);
if (one.equals(two)) 
{
System.out.println(“one and two are equal”);
}
}
}
The String class and the wrapper classes have overridden the equals() method (inherited from class Object), so that you could compare two different objects (of the same type) to see if their contents are meaningfully equivalent. If two different Integer instances both hold the int value 5, as far as you’re concerned they are equal. The fact that the value 5 lives in two separate objects doesn’t matter.
 
public class EqualsTest 
{
public static void main(String args[])
{
String a = “abc”;
String b = “abc”;
//reference a and b are pointing to same String object
System.out.println(“a == b : ” + (a==b));
System.out.println(“a.equals(b) : ” + a.equals(b));
//reference a and c are pointing to different String object but their values are same
String c = new String(“abc”);
System.out.println(“a == c : “+ (a==c));
System.out.println(“a.equals(c) : ” + a.equals(c));
}
}
output:
a == b : true
a.equals(b) : true
a == c : false
a.equals(c) : true
The equals() Contract( as provided in Java docs)
  • It is reflexive. For any reference value x, x.equals(x) should return true.
  • It is symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive. For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  • It is consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
  • For any non-null reference value x, x.equals(null) should return false.
Rate this post

Leave a Reply