简体   繁体   中英

hashCode and compareTo for non-standard equals

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

  1. Do this check -- if yes then return true.
  2. Do null check -- if yes then return false.
  3. Do the instanceof check
  4. Type cast the object
  5. Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks. If first field does not match, don't try to match rest of attribute and return false.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM