An equivalence relation is a relation that satisfies the following three properties:
- Reflexivity
- An object must be equal to itself.
- Formally: a.equals(a)a.equals(a)a.equals(a) must return
true
.
String s = "hello";
System.out.println(s.equals(s)); // true
Symmetry
- If one object is equal to another, then the second must be equal to the first.
- Formally: If a.equals(b)a.equals(b)a.equals(b), then b.equals(a)b.equals(a)b.equals(a) must also be
true
.
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2)); // true
System.out.println(s2.equals(s1)); // true
Transitivity
- If one object is equal to a second, and the second is equal to a third, then the first must be equal to the third.
- Formally: If a.equals(b)a.equals(b)a.equals(b) and b.equals(c)b.equals(c)b.equals(c), then a.equals(c)a.equals(c)a.equals(c) must be
true
.
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("hello");
System.out.println(s1.equals(s2)); // true
System.out.println(s2.equals(s3)); // true
System.out.println(s1.equals(s3)); // true
Additional Considerations
- Consistency: If two objects are equal,
equals()
should always returntrue
as long as their content does not change. - Null Handling: A good
equals()
implementation should returnfalse
when compared withnull
.
Example in a Custom Class
To ensure that equals()
follows the equivalence relation properties, a proper override should be like:
class Person {
String name;
Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // Reflexivity
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return name.equals(person.name); // Content comparison
}
}
This ensures reflexivity, symmetry, and transitivity, making equals()
a valid equivalence relation.