java 对象相同,如何为Java对象定义“相同性”?

小编典典

您应该为自定义类型覆盖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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值