When we override the
equals
method of a class, the argument of the method should have Object
type. But why a more specific type for the argument does not work?In fact, the problem is that it may or may not work depending on how we use it. In the code below, we define the
EqualsDemo
class. We intentionally not override the equals
method. As we can see in the output, the equal test in the if condition works as expected because instance2
is of type EqualsDemo
and the equals
method of EqualsDemo
class is used.However the behavior of the
equals
method is not what we expect when we use it in a set. The output of the program indicates that the equals
method of EqualsDemo
is not invoked. Here is one possible explanation of this behavior. The Set<T>
is a generic type. Due to the type erasure, the parameter type in the compiled code of the definition of Set<T>
is Object
. That's why when comparing the two instances the equals
method of Object is used. The equals
method of EqualsDemo
is not invoked and the two instances are considered as different. That's why the size of theTherefore, when overriding the equals method, the type of argument is always
Object
and do leverage the @Override
annotation!Here is the code:
import java.util.HashSet;
import java.util.Set;
public class EqualsDemo {
public boolean equals(EqualsDemo other) {
System.out.println("equals(EqualsDemo) is called");
return true;
}
public int hashCode() {
return 10;
}
public static void main(String[] args) {
EqualsDemo instance1 = new EqualsDemo();
EqualsDemo instance2 = new EqualsDemo();
System.out.println("equality test in if condition: ");
if (instance1.equals(instance2)) {
System.out.println("two instances are equal.");
}
else {
System.out.println("two instances are not equal");
}
System.out.printf("%nequality test in a set:%n");
Set<EqualsDemo> s = new HashSet<>();
s.add(instance1);
s.add(instance2);
System.out.println("Size of set: " + s.size());
}
}
Here is the output of the program.
equality test in if condition: equals(EqualsDemo) is called two instances are equal. equality test in a set Size of set: 2
----- END -----
©2019 - 2022 all rights reserved