How to generate a hash code from three longs

Joshua Bloch tells you how to write equals and hashCode for your Coordinate class in chapter 3 of his "Effective Java".

Like this:

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;
    }
}

This is an old question, but if anyone bumps into it, now there is an easier way to do it:

@Override 
public int hashCode() {
    return Objects.hash(x, y, z);
}

In Java, the standard hashCode() method returns int, which is 32 bits.

The long datatype is 64 bits. Therefore, three longs means 192 bits of information, which of course cannot be uniquely mapped into just 32 bits of hash value by any hash function.

However, a HashMap will not require unique hashing, it will simply handle the collisions when they occur.

A naive way would be to build the string, i.e. "x,y,z", then hash the string.

You could also try just XOR:ing the values together:

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