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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With