?????????????????п???д???????????????У???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