This question is a result of the responses submitted to my post at CodeReview.
I have a class
called Point
, which is basically "intended to encapsulate a point represented in 2D space." I have overrided the hashcode()
function which is as follows:
...
@Override
public int hashCode() {
int hash = 0;
hash += (int) (Double.doubleToLongBits(this.getX())
^ (Double.doubleToLongBits(this.getX()) >>> 32));
hash += (int) (Double.doubleToLongBits(this.getY())
^ (Double.doubleToLongBits(this.getY()) >>> 32));
return hash;
}
...
Let me clarify (for those who didn't check the above link) that my Point
uses the two double
s: x
and y
to represent its coordinates.
Problem:
My Problem is evident when I run this method:
public static void main(String[] args) {
Point p1 = Point.getCartesianPoint(12, 0);
Point p2 = Point.getCartesianPoint(0, 12);
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
}
I get the Output:
1076363264
1076363264
This is clearly a problem. Basically I intend my hashcode()
to return equal hashcodes for equal Points. If I reverse the order in one of the parameter declarations (i.e. swap 12
with 1
in one of them to get equal Point
s), I get the correct (same) result. How can I correct my approach while maintaining the quality or uniqueness of the hash?