Inconsistent hash code and equal to java

After research, I still can’t find a specific solution to my problem. I have an approximately equal method that epsilon uses, while my hashCode method uses exact values. This violates the HashSet precondition 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 cannot find a way to make hasCode () compatible with my equals method.

+4
source share
2 answers

Your equalsself terminates the contract even before you move on to hashCode, because it is not transitive.

hashCode, , ( ) ,

  • ,

  • hashCode,

  • hashCode.

, .

+6

Kayaman: equos methos, EPoints (pointA, pointB pointC) :

pointA.equals(pointB) //true
pointA.equals(pointC) //true
pointB.equals(pointC) //false

. .

" " -, :
EPoint EPoint . , , EPoint lat lon, , EPoint EPoint int.
, , ,... ).

equals() hashcode() "" , :

@Override
public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof EPoint)) {
        return false;
    }
    EPoint ePoint = (EPoint) o;
    return this.gridLon() == ePoint.gridLon() && ePoint.gridLat() == this.gridLat();
}

@Override
public int hashCode() {
    return Objects.hash(this.gridLon(), this.gridLat());
}
+2

Source: https://habr.com/ru/post/1688405/


All Articles