我有一个带有两个浮点变量的类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()