How to fix my hash function?

This question is the result of answers submitted to my post in CodeReview .


I have class, called Point, which is basically "designed to encapsulate a point represented in 2D space." I redefined a function hashcode()that looks like this:

...
@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 make it clear (for those who have not checked the link above) that mine Pointuses two doubles: xand yto represent its coordinates.

Problem:
My problem is obvious 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

. , , hashcode() - . (.. Swap 12 1 , Point s), ( ) . , ?

+4
4

, Arrays.hashCode ?

  Arrays.hashCode(new double[]{x,y});

, guava , , Objects.hashCode.

Java 7, :

 Objects.hash(x,y)
+1

- , , , .

?

int 32- , 64- (. Java).

, 128 32- , .

  • -, - , .
  • - , / , , . , .
  • - , getX getY .
+5

public int hashCode() {
    long bits = Double.doubleToLongBits(x);
    int hash = 31 + (int) (bits ^ (bits >>> 32));
    bits = Double.doubleToLongBits(y);
    hash = 31 * hash + (int) (bits ^ (bits >>> 32));
    return hash;
}

Arrays.hashCode(double a[]). -:

-992476223
1076364225

- Java. 9

+3

It might be a dumb idea if you use +, which is a symmetric operation, and you get problems with symmetry. What if you use an asymmetric operation such as division (although for the denominator == 0) or minus? Or any other that you find in the literature or invent.

+1
source

Source: https://habr.com/ru/post/1535004/


All Articles