4

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;
}
thpthp
  • 93
  • 1
  • 3

1 Answers1

12

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;
}
Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Eh, you can get nicer than that `Comparator.comparing(Coordinates::getRow).thenComparing(Coordinates::getColumn).compare(this, that)` – Michael Aug 06 '19 at 12:44
  • Thank you for your answer. What about String. Is the first method also safer for String? – thpthp Aug 06 '19 at 12:44
  • @thpthp that would depend on how the two methods will look for `String`s. Are you doing any subtraction when comparing Strings? – Eran Aug 06 '19 at 12:47