In the code below why is it that o1.equals(o2); calls equals(Object o) not the equals(EqualsTest et) even though o1 and o2 are referencing objects of type EqualsTest!
public class EqualsTest {
public static <T> boolean equalTest(T o1, T o2) {
return o1.equals(o2);
}
public static void main(String[] args) {
EqualsTest et1 = new EqualsTest();
EqualsTest et2 = new EqualsTest();
System.out.println(et1.equals(et2));
System.out.println(equalTest(et1, et2));
}
public boolean equals(Object o) {
if (o instanceof EqualsTest) {
System.out.println("equals(Object)");
return true;
}
return false;
}
public boolean equals(EqualsTest et) {
System.out.println("equals(EqualsTest)");
return this.equals((Object)et);
}
}
Type Erasureis doing its jobequals(X)method except forequals(Object), FYI. It'll only get you confused, and won't get used when you expect it to.equals-- likeHashSet-- has to worry about the case where two objects of different types can be unequal, so it has to use theequals(Object)version, and the overload rules mean that it won't call yourequals(EqualsTest)version. It's sort of weird at first, but it really is the only approach that makes sense in all cases.public static <EqualsTest> boolean equalTest(EqualsTest o1, EqualsTest o2), then the program would callequals(EqualsTest et)?