@Edit: I'm using this library http://jqno.nl/equalsverifier/ to check if equals
and hashCode
are written properly.
Let's say we have this class:
final class Why {
private final int id;
private final String name;
Why(final int id, final String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof Why)) return false;
final Why why = (Why) o;
if (id != why.id) return false;
return name != null ? name.equals(why.name) : why.name == null;
}
@Override
public int hashCode() {
return id;
}
}
In hashCode
I'm relaying only on id
field, because this will give me pretty good, non colliding hashes. Worth noticing is this hash
method comply with all rules for equals-hashCode
. I don't want do some fancy tricks with summing hashes, i.e. this:
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
So could you explain me why EqualsVerifer
by default demand using all fields from equals
method in hashCode
method?
java.lang.AssertionError: Significant fields: equals relies on subValue, but hashCode does not.