简体   繁体   中英

Why is this set containment check failing?

I am going through the Effective Java 3rd edition and I was reading Item 10: Follow Equals contract when overriding.

There is an example there which I was trying to simulate on my machine. Below is the code for the same.

public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Point))
            return false;

        Point p = (Point)obj;
        return (x == p.x) && (y ==p.y);
    }

    // Use this for demonstration with AtomicPoint class.
    /*@Override
    public boolean equals(Object obj) {
        if(obj == null  || (obj.getClass() != getClass())) {
            return false;
        }

        Point p = (Point)obj;

        return p.x == x && p.y == y;
    }*/
}

public class AtomicPoint extends Point{
    private static final AtomicInteger counter = new AtomicInteger();

    public AtomicPoint(int x, int y) {
        super(x, y);
        counter.incrementAndGet();
    }

    public static int getCounter() {
        return counter.get();
    }

    private static Set<Point> sampleSet = new HashSet<>();

    public static void main(String[] args) {
        sampleSet.add(new Point(1,2));
        sampleSet.add(new Point(1,3));
        sampleSet.add(new Point(1,4));

        AtomicPoint ap = new AtomicPoint(1,3);

        // This should return true but its returning false
        System.out.println(sampleSet.contains(ap));
    }
}

As you can see from the comment in the AtomicPoint class, I am getting false for the contains check, whereas Joshua Bloch states that this should return true. Can someone help me here?

For using HashSet<T> or HashMap<T> you need to override hashCode() methods from super class. You should have in your editor automatically generating hashCode() and equals() methods (and i'm suggesting you to use that always in every class). If you want to use TreeSet<T> or TreeMap<T> you will need to implement Comparable or Comparator<T> interface and override their compare() or compareTo() methods for using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM