Search code examples
javacoordinatespriority-queuecomparator

Java Override CompareTo method


I have Coordinates class and I want to make Coordinates object comparable.

public class Coordinates implements Comparable<Coordinates> {

private int row;
private int column;

The idea is to insert Coordinates objects into PriorityQueue and to get them out sorted.

 @Override
public int compareTo(Coordinates o) {
    if (row < o.row) {
        return row;
    }
    if (row > o.row) {
        return o.row;
    }
    if (row == o.row) {
        if (column < o.column) {
            return column;
        }
        if (column > o.column) {
            return o.column;
        }
    }
//    return 0;
}

This is my attempt but I am not sure what exactly am I expected to return and how to return it. I want my smallest coordinates to have highest priority. And the function I wrote still expects a return value - the commented line


Solution

  • I want 0,5 to have highest priority than 1,5 and 1,0 to have higher priority than 1,3

    In effect you want a reverse sort. However, a priority queue places the lowest values first so natural order make the lowest values to appear first.

    You want to return <0 for less than and >0 for greater than

    @Override
    public int compareTo(Coordinates o) {
        if (row < o.row) return -1;
        if (row > o.row) return +1;
    
        if (column < o.column) return -1;
        if (column > o.column) return +1;
        return 0;
    }
    

    You can simplify this with Integer.compare

    @Override
    public int compareTo(Coordinates o) {
        int cmp = Integer.compare(row, o.row);
        if (cmp == 0)
            cmp = Integer.compare(column, o.column);
        return cmp;
    }
    

    Note: if you assume row and column are non-negative you can write

    @Override
    public int compareTo(Coordinates o) {
        int cmp = row - o.row;
        if (cmp == 0)
            cmp = column - o.column;
        return cmp;
    }