How to generate a hash code from three longs

Samuel picture Samuel · Apr 20, 2011 · Viewed 10.3k times · Source

I have a HashMap with coordinates as keys.

Coordinates have 3 longs holding the x, y and z coordinate. (Coordinate is and needs to be a custom class, the coordinates need to be longs).

Now i want to be able to access e.g. the field [5, 10, 4] by doing: hashMap.get(new Coordinate(5, 10, 4)).

I have implemented the equals method but that is not enough since apparently i need to provide an implementation for hashCode as well. So my question is how do i generate an unique hashCode from three longs?.

Additional: Using a hash generator from an external library is not option.

Answer

duffymo picture duffymo · Apr 20, 2011

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