我使用的是自定义类Vec
在HashMap
的关键。具有相同的hashCode相等的对象不映射到相同值的HashMap
但是两个相等Vec
对象具有相同hashCode()
不会映射到相同的密钥。
我在做什么错?
import java.util.HashMap;
/**
* A 2-element float Vector
*/
class Vec {
public float x;
public float y;
public Vec(float x, float y) {
this.x = x;
this.y = y;
}
public Vec(Vec v) {
this.x = v.x;
this.y = v.y;
}
public boolean equals(Vec v) {
System.out.println("equals called");
return (x == v.x &&
y == v.y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = (Float.floatToIntBits(x)
+ prime * Float.floatToIntBits(y));
System.out.println("hash called: " + result);
return result;
}
}
public class Debug {
public static final void main(String[] args) {
Vec v1 = new Vec(3, 5);
Vec v2 = new Vec(v1);
System.out.println("vecs equal: " + v1.equals(v2));
System.out.println("hashcodes: " + v1.hashCode() + ", " + v2.hashCode());
System.out.println("\nuse map");
HashMap<Vec, Object> map = new HashMap<>();
map.put(v1, new Object());
Object o1 = map.get(v1);
Object o2 = map.get(v2);
System.out.println(o1);
System.out.println(o2);
if (o2 == null) {
throw new RuntimeException("expected o2 not to be null");
}
};
}
输出
equals called
vecs equal: true
hash called: 329252864
hash called: 329252864
hashcodes: 329252864, 329252864
use map
hash called: 329252864
hash called: 329252864
hash called: 329252864
[email protected]
null
Exception in thread "main" java.lang.RuntimeException: expected o2 not to be null
因为你didn't覆盖'equals'方法,你是用不同的方法签名,因此它只是一种重载方法。签名需要是“boolean equals(Object)”。你介意张贴相关的代码 – SomeJavaGuy