gpt4 book ai didi

java - Java 中 float 的哈希码

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:41:29 28 4
gpt4 key购买 nike

我有一个包含两个浮点变量和 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com