I am using the hash code builder as an instance variable of a pojo.
public class Pojo {
private HashCodeBuilder hashBuilder = new HashCodeBuilder();
private int i;
public setI(int i) {this.i = i}
@Override
public int hashCode() {
hashBuilder.append(id);
return hashBuilder.toHashCode();
}
}
Now if I set the value of i
to the same value twice, then my hashcode result will be different. Is this a bug in the implementation?
I understand that it is happening because the hash code builder keeps a running total. But should it not give the same hash for the same set of values?
Also, if I don't follow the above approach then I will end up initialising the same hash code builder within the hashcode
method of my pojo thousands of times as follows:
...
@Override
public int hashCode() {
hashBuilder = new HashBuilder();
hashBuilder.append(id);
return hashBuilder.toHashCode();
}
...
Is there a way to reset this running total so that every time I call hashcode
with the same set of values I get a consistent answer?