1

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?

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • are you eventually going to mod by the size of the `Map` so that you don't get an `IndexOutOfBoundsException`? If so you can do a mod somewhere in the code to prevent the overflow. – twain249 Apr 29 '12 at 21:39
  • why are you dividing 1000 by epsilon (which I presume a really small number)? – Luciano Apr 29 '12 at 21:40
  • To differentiate objects that have the same integer coordinates but not the same double coordinates.i.e.: (0.0,0.0) is different from (0.0+EPSILON,0.0). – Ramy Al Zuhouri Apr 29 '12 at 21:45
  • I think the real problem here is that you want to handle `(x,y) equal to (x+eps,y)` which your current hashcode implementation doesn't guarantee. Actually I'm pretty sure you *can't* do this and guarantee transitivity, which means your equals/hashcode is already broken beyond repair – Voo Apr 29 '12 at 21:52

1 Answers1

1

This is how you should do it for doubles (see here):

long t = Double.doubleToLongBits(d);
result = prime * result + (int) (t ^ (t >>> 32));

For prime use a smallish prime number, a standard value is 37.

Initialize result with 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.

Community
  • 1
  • 1
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436