How to create a hash code of three lengths

I have a HashMap with coordinates as keys.

The coordinates have 3 long coordinates x, y and z. (The coordinate is and must be a custom class, the coordinates must be long).

Now I want to have access, for example. Field [5, 10, 4], performing: hashMap.get(new Coordinate(5, 10, 4)).

I applied the equals method, but this is not enough, since, apparently, I also need to implement the hashCode implementation. So my question is: how can I create a unique hash code of three lengths? .

Optional: using a hash generator from an external library is not an option.

+5
source share
4 answers

, equals hashCode Coordinate 3 " Java".

:

public class Coordinate
{
    private long x;
    private long y;
    private long z;

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Coordinate that = (Coordinate) o;

        if (x != that.x) return false;
        if (y != that.y) return false;
        if (z != that.z) return false;

        return true;
    }

    @Override
    public int hashCode()
    {
        int result = (int) (x ^ (x >>> 32));
        result = 31 * result + (int) (y ^ (y >>> 32));
        result = 31 * result + (int) (z ^ (z >>> 32));
        return result;
    }
}
+15

Java hashCode() int, 32 .

long - 64 . , long 192 , , , 32 - -.

, HashMap , , .

, , "x, y, z", hash .

XOR: :

int hashCode()
{
  return (int) (x ^ y ^ z);
}
+3

hashCode ?

. - .

+2
source

You must understand that there is a difference between the hash code and the unique key that will be used in HashMap.

The hash code for your Coordinate class need not be unique ...

A good hash code solution would be:

(int)(x ^ (x >> 32) ^ y ^ (y >> 32) ^ z ^ (z >> 32));

This is the XOR of the two halves of each of the long XOR-ed together.

0
source

All Articles