Comparator.compare(x, y) orders two objects by returning a negative integer, zero, or a positive integer. Clients must inspect the sign, not a particular nonzero value. section 7.0 section 7.9
Implement and consume compare() according to these rules:
- Return zero when the compared values are equivalent under the comparator; return opposite signs when reversing the arguments. section 7.10
- Preserve transitivity: if x is greater than y and y is greater than z, x must be greater than z. section 7.10
- Test results with < 0, == 0, or > 0; never require exactly -1 or 1. section 7.9
- Use nullsFirst() or nullsLast() when the external comparator should define an order involving null. section 7.10
The exact-value trap
This check is fragile: if (comparator.compare(a, b) == 1) { … }. A valid comparator may return 3 or another positive value, especially when delegation reaches String.compareTo(). Write if (comparator.compare(a, b) > 0) instead. section 7.9
Returning zero for equal values
A boolean ordering must distinguish equality: return b == o.b ? 0 : b ? 1 : -1;. Returning -1 for both false values makes an object compare as smaller than itself and violates the contract. section 7.10
Comparator<File> comparator = (file1, file2) -> {
if (file1.isDirectory()) {
return -1;
} else if (file2.isDirectory()) {
return 1;
}
return file1.getName().compareTo(file2.getName());
};
Shows a focused comparator that orders directories before files and delegates file-name ordering to String.compareTo(). section 7.10
