How to generate a hash code from three longs

倾然丶 夕夏残阳落幕 提交于 2019-12-03 14:33:38

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

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

how do i generate an unique hashCode from three longs?

You don't need to. Hash codes are not required to be unique.

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

You should realize there is a difference between a hashcode and the unique key to be used in a HashMap.

The hashcode for your Coordinate class does not have to be unique at all...

A good solution for the hashcode would be:

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

Wich is the XOR of the two halves of each of the longs XOR-ed together.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!