小编典典
您应该为自定义类型覆盖equals和hashCode方法。
但是要小心,您会在这里遇到各种麻烦:例如,如果您的自定义类型具有子类型,则可能会遇到其他相等性问题:
class Point {
final int x;
final int y;
public Point(int x, int y) {
this.x= x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (o == this) return true; //If objects equal, is OK
if (o instanceof Point) {
Point that = (Point)o;
return (x == that.x) && y == that.y);
}
return false;
}
}
class ColoredPoint extends Point {
final Color color;
ColoredPoint(int x, int y, Color color) {
super(x, y);
this.color = color
}
}
Point p1 = new Point(1, 2);
ColoredPoint cp1 = new ColoredPoint(1, 2, Color.BLUE);
ColoredPoint cp1 = new ColoredPoint(1, 2, Color.RED);
就目前而言,p1,cp1和cp2都相等。但是,显然cp1和cp2不相等。您还需要在ColoredPoint中实现一个等于,以比较ColoredPoint对象(但是这会破坏p1和cp1或cp2之间的相等性)。
另外,请确保您的对等人上面有签名。将其定义为public equals(Point that)...是一个常见的错误,这是错误的。
2020-11-19