-2
import java.util.TreeMap;

class Point implements Comparable<Point>{
    private int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object arg0) {
        Point p = (Point) arg0;
        return (this.x == p.x && this.y == p.y);
    }

    @Override
    public String toString() {
        return "("+x+", "+y+")";
    }

    @Override
    public int compareTo(Point arg0) {
        if(this.x == arg0.x && this.y == arg0.y)
            return 0;
        return -1;
    }

}

public class Test {
    static int row, col;
    static TreeMap<Point, Integer> dist;
    public static void main(String[] args) {
        dist = new TreeMap<>();
        row = 4;
        col = 7;
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                Point p = new Point(i, j);
                dist.put(p, Integer.MAX_VALUE);
            }
            if(i >= 1)
                System.out.println(i+": "+dist.keySet().contains(new Point(1, 5)));
        }
    }
}

The output should be: 1: true 2: true 3: true

but its coming 1: true 2: false 3: false

can some one please explain why is this output coming? this code is working fine if i am taking predefined data types as key to the map. can some one please explain why is this output coming? this code is working fine if i am taking predefined data types

as key to the map.

Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
Prince
  • 11
  • 2

2 Answers2

2

Your compareTo is not transitive anti-symmetric. See here for more detail.

@Override
public int compareTo(Point arg0) {
    if(this.x == arg0.x && this.y == arg0.y)
        return 0;
    return -1;
}

When a!=b, a.compareTo(b) returns -1, but b.compareTo(a) also returns -1. This leads to incorrect sorting.

Community
  • 1
  • 1
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
2

As @RobAu points out, the problem is your compareTo method. Note the documentation of that method:

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

You need to modify your code to allow for proper comparison between points, that is, you have to come up with some ordering for points. For instance, here is an alternative implementation that works:

@Override
public int compareTo(Point arg0) {
    int ret = Integer.compare(x, arg0.x);
    if (ret == 0) {
        ret = Integer.compare(y, arg0.y);
    }
    return ret;
}
Thomas
  • 17,016
  • 4
  • 46
  • 70
  • @Prince No worries -- but I think it would be fairer to give user `RobAu` the credit, his answer was correct (and before mine) I just added the quote and the code example. – Thomas Apr 12 '17 at 07:14