0

I need a hash function to overide the hashCode() method from the object class.

I have a Point class that represents a point on coordinate grid. The instance variables are double x, y;

I also have methods

public int getX(){
 return Math.round(x);
}

public int getY(){
   Math.round(y);
}

How can I create a hash function that will return an integer? Would a simply put

return Math.round(getX()/getY());

work?

TemporaryFix
  • 2,008
  • 3
  • 30
  • 54
  • 1
    The aim of a hash function is to uniformly distribute values between 0 and 2^32 - 1. Does your function do that? – Oliver Charlesworth Jan 25 '14 at 21:24
  • Well how are you defining equality, first? Why do you have `double` variables if you're rounding in the getters? Are they actually intended to be more than integers, usefully? – Jon Skeet Jan 25 '14 at 21:24
  • There are going to be a lot of hash collisions if you do it this way... For example, 6/3 = 2 and 4/2 = 2; – 1110101001 Jan 25 '14 at 21:25

1 Answers1

1

Your IDE most likely has a utility to generate hash code and equals for you, look under the source or insert code menus.

All you need to do though is return getX()+31*getY();

See this question and answer for more detailed discussion on the theory of hash codes:

Best implementation for hashCode method

Community
  • 1
  • 1
Tim B
  • 40,716
  • 16
  • 83
  • 128