我有以下代码:
import java.util.*;
class A {
int x;
A() { x = 0; }
A(int t) { x = t; }
public int hashCode() { return x; }
public boolean equals(A that) { return x == that.x; }
}
class Test {
static HashMap<A, Integer> stuff;
public static void main(String[] args) {
stuff = new HashMap<A,Integer>();
A a = new A(1);
stuff.put(a, 100);
System.out.println(stuff.get(a).toString());
System.out.println(stuff.get(new A(1)).toString());
}
}
Run Code Online (Sandbox Code Playgroud)
为什么第二个印刷声明给我一个NullPointerException?
awk*_*ksp 16
你不是压倒一切equals().正确的签名是
public boolean equals(Object o)
^^^^^^
Run Code Online (Sandbox Code Playgroud)
请注意,类型是Object,而不是A.你做的是超载equals().
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |