Inconsistent hashcode and equals java

Alex Blasco :

After researching I still can't find the specific solution for my problem. I have an "approximately equals" method that uses an epsilon, while my hashCode method uses the exact values. This breaks the precondition of HashSet when I compare the values.

@Override
public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof EPoint)) {
        return false;
    }
    EPoint ePoint = (EPoint) o;
    return Math.abs(Math.abs(ePoint.lat) - Math.abs(lat)) < EPSILON && Math.abs(Math.abs(ePoint.lon) - Math.abs(lon)) < EPSILON;
}

@Override
public int hashCode() {
    return Objects.hash(lat, lon);
}

I can't find a way to make the hasCode() consistent with my equals method.

Alexey Romanov :

Your equals itself breaks the contract even before you get to hashCode because it isn't transitive.

This also immediately leads to the only consistent hashCode implementation being to return a constant, because for any two points there is a (very long) chain of intermediate points so that

  1. every two neighbors are equal, therefore

  2. every two neighbors must have the same hashCode, therefore

  3. beginning and end must have the same hashCode.

Now, this is a consistent implementation, but quite obviously a useless one.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473874&siteId=1