liveBook · Manning

Comparator.compare

As explained in 100 Java Mistakes and How to Avoid Them

The compare method is the Comparator method that returns a negative, zero, or positive integer according to the ordering of two arguments.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines sign, antisymmetry, transitivity, null handling, and failure modes, but does not develop comparator design beyond focused examples.
Examples
Uses boolean ordering, directory-versus-file ordering, filename delegation, and a user record ordered by name then age.
What it assumes
Assumes familiarity with Java objects and distinguishes external Comparator ordering from Comparable natural ordering.
What you can do after
Diagnose comparator bugs by checking result signs, contract laws, null policy, and accidental dependence on exact return values.
How it connects
Connects Comparator.compare() with Comparable.compareTo(), natural ordering, String.compareTo(), Integer.compare(), and sorting algorithms.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.