java - Java 中 float 的哈希码

标签 java floating-point hashcode

我有一个包含两个浮点变量和 hashCode 方法的类(当前代码片段中没有 equals):

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() :

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

来自 Javadoc:

public static int hash(Object... values)

Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]). This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x, y, and z, one could write:

关于java - Java 中 float 的哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36848151/

相关文章:

java - 在单个结构中插入多个 ArrayList

java - Map/reduce java - 创建未知输出的代码

java - .NET 相当于内部类型数组的 java.util.Arrays.hashCode() 函数?

ruby-on-rails - Ruby float 学 - Sum Calc 中的精度问题

php - 为什么 PHP 使用 Zend_Amf 将数字 16 转换为 float(6.1026988574311E_320)

java - 来自反射的哈希码?

java - 如何在java中使用MessageDigest类?

java - Spring MVC CrudRepository findByIn

java - 移植C代码;需要有关按位运算和指针语法的帮助

c++ - 如何确定 float 的上限和下限?