Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two compareTo methods?

I want to understand what is the difference between these two methods? Can they both be used for the same problem? Or are they designed for different cases?

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;
}
@Override
public int compareTo(Coordinates o) {
    int cmp = row - o.row;
    if (cmp == 0)
        cmp = column - o.column;
    return cmp;
}
like image 718
thpthp Avatar asked Dec 13 '22 10:12

thpthp


1 Answers

The two methods have similar behavior: they would return a negative value if row < o.row and positive value if row > o.row. If row == o.row, they would return a negative value if column < o.column and positive value if column > o.column. If both row==o.row and column==o.column, they would return 0.

This means that both methods can be used to sort a list of Coordinates, first by the row parameter and then by the column parameter.

However, the first method is safer.

The second method can fail due to numeric overflow. If, for example the result of row - o.row should be smaller than Integer.MIN_VALUE, the actual result of the subtraction will become positive even though row is smaller than o.row.

Of course, in order not to re-invent the wheel, it would be better to rely on Integer.compare() and write:

public int compareTo(Coordinates o) {
    int res = Integer.compare(row,o.row);
    return res == 0 ? Integer.compare(column,o.column) : res;
}
like image 88
Eran Avatar answered Mar 06 '23 18:03

Eran