Java equals and hash code Contract

If two objects are equal, the hash code must be the same.

But the same hash code does not guarantee that two objects are equal.

Code example for a proper implementation:

 @Override
    public final boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof MyClassOrInterface)) {
            //some do prefer #getClass but I don't
            return false;
        }
        MyClassOrInterface that = (MyClassOrInterface) o;
        return Objects.equals(this.hashCode(), that.hashCode()) &&
                Objects.equals(name, that.name) &&
                Objects.equals(sessionId, that.sessionId);
    }

    @Override
    public final int hashCode() {
        return Objects.hash(name, sessionId);
    }

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.