如何从三个long生成哈希码 [英] How to generate a hash code from three longs
问题描述
我有一个坐标为键的HashMap。
I have a HashMap with coordinates as keys.
坐标有3个长整数,包含x,y和z坐标。 (坐标是并且需要是自定义类,坐标需要很长)。
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).
现在我希望能够访问例如字段[5,10,4]: hashMap.get(新坐标(5,10,4))
。
Now i want to be able to access e.g. the field [5, 10, 4] by doing: hashMap.get(new Coordinate(5, 10, 4))
.
我已经实现了equals方法,但这还不够,因为显然我还需要为hashCode提供一个实现。所以我的问题是如何从三个长度生成一个唯一的hashCode? b>。
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.
推荐答案
Joshua Bloch告诉您如何在第3章他的Effective Java。
Joshua Bloch tells you how to write equals and hashCode for your Coordinate class in chapter 3 of his "Effective 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;
}
}
这篇关于如何从三个long生成哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!