以下映射的第一个值应被第三个值覆盖,但事实并非如此。为什么?
导入java.util.*;
class A
{
int a, b;
A(int a,int b) {
this.a = a;
this.b = b;
}
public boolean equals(A aa) {
if(this.a == aa.a && this.b == aa.b) {
return true;
}
return false;
}
public int hashCode() {
return this.a-this.b;
}
}
主类
public class MyClass { // main class
public static void main(String args[]) { // main method
Map<A,Character> map = new LinkedHashMap<>();
map.put(new A(1,2),'a'); //first
map.put(new A(1,3),'b'); //second
map.put(new A(1,2),'v'); //third
for(A a : map.keySet()) {
System.out.println(a.a+" "+a.b+" "+map.get(a));
}
}
}
代码的输出是:
1 2a
1 3 b
1 2 v
最佳答案
您正在重载equals
方法,而不是覆盖它。正确的签名是equals(Object)
:
public boolean equals(Object o) {
if (!(o instanceof A)) {
return false;
}
A aa = (A) o;
if(this.a == aa.a && this.b == aa.b) {
return true;
}
return false;
}
将来避免这些错误的一个好方法是使用 @Override
注释来注释您尝试覆盖的方法 - 如果您有错误的签名,编译器将发出错误,就像您以前那样在这里。
关于java - 为什么 map 的第一个值不被第三个值覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61234048/