?????Java?б???equals?????????????壨?£?
???????????? ???????[ 2012/9/18 10:13:57 ] ????????
?????????????????п???д???????????????У???ColoredPointed?????????hashCode??????μ?ColoredPoint?????equals???壬??????????Point??equals????塣hashCode??淶???????Ч??????????????(colored point)???????????????????????hashCode?????????????????
????????ColoredPoint?????????????????????????????????ColoredPoint??Point?????б???????????
Point p = new Point(1?? 2);
ColoredPoint cp = new ColoredPoint(1?? 2?? Color.RED);
System.out.println(p.equals(cp)); // ????? true
System.out.println(cp.equals(p)); // ????? false
????“p?????cp”???????????????????Point?????equals??????????????????????????????????????檔??????????棬“cp?????p”???????????????????ColoredPoint?????equals????????????????false?????????p????ColoredPoint??????equals???????Υ?????????
????Υ?????????????????????2????????????????磺
Set<Point> hashSet1 = new java.util.HashSet<Point>();
hashSet1.add(p);
System.out.println(hashSet1.contains(cp)); // ??? false
Set<Point> hashSet2 = new java.util.HashSet<Point>();
hashSet2.add(cp);
System.out.println(hashSet2.contains(p)); // ??? true
??????????p??cp??????????contains?????????????????????????????????
????????????equals????壬????????????????????????????????????????????????????????????????????????????????????????a??b??????????ж?????????a??b????b??a ??????true???????????
public class ColoredPoint extends Point { // Problem: equals not transitive
private final Color color;
public ColoredPoint(int x?? int y?? Color color) {
super(x?? y);
this.color = color;
}
@Override public boolean equals(Object other) {
boolean result = false;
if (other instanceof ColoredPoint) {
ColoredPoint that = (ColoredPoint) other;
result = (this.color.equals(that.color) && super.equals(that));
}
else if (other instanceof Point) {
Point that = (Point) other;
result = that.equals(this);
}
return result;
}
}
??????ColoredPoint?е?equals??????????????м???????????:????????????Point?????????ColoredPoint??????????Point???equals???????á?????????????Ч????equals???????????”cp.equals(p)”????”p.equals(cp)”????????true??????????????equals??淶??????????????????????????μ?????????????????????????δ????????????????????????????????????????
ColoredPoint redP = new ColoredPoint(1?? 2?? Color.RED);
ColoredPoint blueP = new ColoredPoint(1?? 2?? Color.BLUE);
????redP?????p??p?????blueP
System.out.println(redP.equals(p)); // prints true
System.out.println(p.equals(blueP)); // prints true
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11