So, rather than calculating the hash code every time, I thought I could keep an integer updated with all the changes. Imagine a setter for a property that contributes to the hash code:
public void setFoo(Foo newFoo){
this.hashCalculator.remove(this.foo.hashCode()); // remove old hash code
this.hashCalculator.add(newFoo.hashCode()); // add new hash code
this.foo = newFoo; // set new foo
}
(I hope I'm not doing something stupid) I thought it would be simple math, but I am failing at implementing it. I think it has something to do with overflowing integers but I'm not sure. Clearly I'm missing something. The remainder from the division should probably be added back to the value, right?
This is the code I have. At the end the result should be 1, but it's not what I get.
class HashCode
{
public int value = 1;
public void add(int val){
// as suggested by effective java
value = value * 37 + val;
}
public void remove(int val){
value = (value - val) / 37;
}
}
HashCode o = new HashCode();
for(int a = 0; a < 1000; a++){
o.add(a);
}
for(int r = 0; r < 1000; r++){
o.remove(r);
}
System.out.println(o.value); // should be 1