I have a class having two methods: getY() and getX() (it’s a sort of map).
Y’s and X’s domain is [-1000.0, + 1000.0], and they’re doubles.
I have written a hashCode() method:
@Override
public int hashCode()
{
int hash=(int) (getX()/EPSILON);
hash+= (int) ( (1000.0/EPSILON)*getY() );
return hash;
}
Where EPSILON is the maximum error tolerated.
But the problem is that values are too high and I get an overflow if X=1000.0 and Y=1000.0 .
How to write a hashCode() method that handles the overflow and is still able to return two hash codes for two different objects in every case?
This is how you should do it for doubles (see here):
For
primeuse a smallish prime number, a standard value is 37.Initialize
resultwith another prime, don’t start from zero. Standard for that is 17.This is from Effective Java by Josh Bloch.
As far as your immediate questions:
You handle overflow by ignoring it. Overflow is welcome in hash code calculation.
Of course you cannot guarantee distinct hash for every possible value. The goal is good dispersion, not uniqueness.