Java 中浮点数的哈希码

2024-02-16

我有一个带有两个浮点变量的类hashCode方法(当前代码片段中没有等于):

public class TestPoint2D {
    private float x;
    private float z;

    public TestPoint2D(float x, float z) {
        this.x = x;
        this.z = z;
    }

    @Override
    public int hashCode() {
        int result = (x != +0.0f ? Float.floatToIntBits(x) : 0);
        result = 31 * result + (z != +0.0f ? Float.floatToIntBits(z) : 0);
        return result;
    }
}

以下测试

@Test
public void tempTest() {
    TestPoint2D p1 = new TestPoint2D(3, -1);
    TestPoint2D p2 = new TestPoint2D(-3, 1);

    System.out.println(p1.hashCode());
    System.out.println(p2.hashCode());
}

返回相同的值:

-2025848832

在这种情况下,我无法在 HashSet / HashMap 中使用我的 TestPoint2D

谁能建议如何实施hashCode在这种情况下或与此相关的解决方法?

附: 添加了一项测试:

@Test
public void hashCodeTest() {
    for (float a = 5; a < 100000; a += 1.5f) {
        float b = a + 1000 / a; // negative value depends on a
        TestPoint3D p1 = new TestPoint3D(a, -b);
        TestPoint3D p2 = new TestPoint3D(-a, b);
        Assert.assertEquals(p1.hashCode(), p2.hashCode());
    }
}

并且通过了证明

TestPoint2D(a, -b).hashCode() == TestPoint2D(-a, b).hashCode()


我会用Objects.hash() https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#hash-java.lang.Object...-:

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

来自 Javadoc:

public static int hash(Object... values)

为输入值序列生成哈希码。生成哈希码的方式就好像所有输入值都放入一个数组中,并且该数组通过调用 Arrays.hashCode(Object[]) 进行哈希处理。 此方法对于在包含多个字段的对象上实现 Object.hashCode() 非常有用。例如,如果一个对象具有 x、y 和 z 三个字段,则可以编写:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 中浮点数的哈希码 的相关文章

随机推荐