Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Significant fields: hashCode relies on field, but equals does not #244

Closed
JohT opened this issue Aug 25, 2019 · 1 comment
Closed

Significant fields: hashCode relies on field, but equals does not #244

JohT opened this issue Aug 25, 2019 · 1 comment

Comments

@JohT
Copy link

JohT commented Aug 25, 2019

"hashcode" does not need to use all fields of "equals".
Of course, It is not allowed to use fields, that are not part of "equals".
But it should be perfectly valid, if "hashcode" only uses a subset of the fields in "equals".
It should also be perfectly valid, to return a constant value like 42. It may lead to performance issues within large HashMaps, but it fulfills the contract.

The following test fails with version 3.1.9, but it shouldn't (IMO):
@test
@DisplayName("equals and hashcode fulfill the contract")
void testEqualsAndHashcodeFulfillTheContract() {
EqualsVerifier.forClass(ValueObject.class).usingGetClass().verify();
}
static class ValueObject {
private final String id;
private final String info;

    public ValueObject(String id, String info) {
        this.id = id.trim();
        this.info = info.trim();
    }
    public String getId() {
        return id;
    }
    public String getInfo() {
        return info;
    }
    @Override
    public boolean equals(final Object other) {
        if ((other == null) || (!getClass().equals(other.getClass()))) {
            return false;
        }
        ValueObject castOther = (ValueObject) other;
        return Objects.equals(id, castOther.id) && Objects.equals(info, castOther.info);
    }
    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }
}
@JohT
Copy link
Author

JohT commented Aug 25, 2019

Sorry, this was already fixed with #142.

@JohT JohT closed this as completed Aug 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant