下面的代码返回false。试图使方程对象充当自定义HashMap中的键。非常确定方法覆盖实现正确,hashCode在两个方程实例之间是完全相同的。到底出了什么问题?
class Solution {
public boolean maxPoints(int[][] points) {
Map<Equation, Integer> map = new HashMap<>();
Equation eq1 = new Equation(1, 2);
Equation eq2 = new Equation(1, 2);
map.put(eq1, 1);
if (map.containsKey(eq1)) return true;
return false;
}
class Equation {
private int slope;
private int yIntercept;
public Equation(int slope, int yIntercept) {
this.slope = slope;
this.yIntercept = yIntercept;
}
public boolean equals(Equation other) {
if (other == this) return true;
return (this.slope == other.slope && this.yIntercept == other.yIntercept);
}
public int hashCode() {
return Objects.hash(this.slope, this.yIntercept);
}
}
}
如果您想覆盖一个方法,请用@Override
注释它。编译器会给你一个equals
错误,因为你没有覆盖而是重载
@Override
public boolean equals(Object other) {
...
}
equals
需要为public boolean equals(Object other)
才能匹配Object
中的签名
你的equals
方法不会覆盖HashMap
中代码正在调用的方法。
通常equals
方法是这样的:
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Equation)) {
return false;
}
// instanceof above also covers null
Equation otherEquation = (Equation) other;
return otherEquation.slope == this.slope
&& otherEquation.yIntercept == this.yIntercept;
}
…或者使用Project Lombok的@EqualsAndHashCode
注释。