Search code examples
javatreemap

Why is is my TreeMap not sorted correctly?


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.


Solution

  • 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.