二维坐标的良好哈希码函数

I L*_*ode 3 java hash hashmap hashcode

我想使用 aHashMap 将 (x, y) 坐标映射到值。什么是好的hashCode()函数定义?在这种情况下,我只为某些参数 M 存储形式为 (x, y) 的整数坐标,其中 y - x = 0, 1, ..., M - 1。

Man*_*ani 7

要从两个数字中获取唯一值,您可以使用此处描述的双射算法 < x; y >= x + (y + ( (( x +1 ) /2) * (( x +1 ) /2) ) )

这将为您提供 unquie 值,可用于哈希码

public int hashCode()
{
      int tmp = ( y +  ((x+1)/2));
               return x +  ( tmp * tmp);
}
Run Code Online (Sandbox Code Playgroud)


mar*_*kli 1

为了计算具有多个属性的对象的哈希码,通常会实施通用解决方案。该实现使用常数因子来组合属性,因子的值是讨论的主题。似乎 33 或 397 的因子通常会导致散列码的良好分布,因此它们适合字典。

这是 C# 中的一个小示例,但它应该很容易适用于 Java:

public override int GetHashCode()
{
  unchecked // integer overflows are accepted here
  {
    int hashCode = 0;
    hashCode = (hashCode * 397) ^ this.Hue.GetHashCode();
    hashCode = (hashCode * 397) ^ this.Saturation.GetHashCode();
    hashCode = (hashCode * 397) ^ this.Luminance.GetHashCode();
    return hashCode;
  }
}
Run Code Online (Sandbox Code Playgroud)

此方案也适用于您的坐标,只需将属性替换为 X 和 Y 值即可。注意,我们应该防止整数溢出异常,在DotNet中这可以通过使用块来实现unchecked