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?

4
  • 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. Commented Apr 29, 2012 at 21:39
  • why are you dividing 1000 by epsilon (which I presume a really small number)? Commented Apr 29, 2012 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). Commented Apr 29, 2012 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 Commented Apr 29, 2012 at 21:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.