Given following implementation of equals:
public class Test implements Comparable<Test> {
private int x, y;
@Override
public boolean equals(Object obj) {
if (obj instanceof Test) {
Test other = (Test) obj;
return x == other.x || y == other.y;
}
return false;
}
@Override
public int hashCode() {
//implementation?
}
@Override
public int compareTo(Test o) {
//implementation?
}
}
What is correct/most performant implementation of hashCode and compareTo? Please note - equals uses OR , not AND
equals() method is used to determine the equality of two objects.
When we say equality, it should adhere by the following properties,
Reflexive : Always, a = a. In Java, a.equals(a) should always be true.
Symmetric : If a = b, then b = a. In Java, if a.equals(b) is true, then b.equals(a) should be true.
Transitive : If a = b and b = c, then a = c. In Java, if a.equals(b) and b.equals(c) is true, then a.equals(c) should be true.
Your equals() doesnot confront to this rules.
Moreover according to javadoc - It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals . So we may face some problem using this implementation of equals() while natural sorting
Good approach for overriding equals method in Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.