liveBook · Manning

Sequence of keys

As explained in 100 Java Mistakes and How to Avoid Them

A sequence of keys is an ordered set of object values compared lexicographically to determine object ordering.

Represent an object as ordered comparison keys and compare them lexicographically: compare the first key, then consult later keys only when earlier keys are equal. This keeps compareTo implementations aligned with the comparison contract. section 7.13

Special cases must become keys

A comparator that returns -1 whenever this connection is secure mishandles two secure connections. Model security as the first key and url as the second, using Boolean.compare or ComparisonChain; otherwise swapping equal-category objects can violate the contract. section 7.13

Comparator<Person> PERSON_COMPARATOR =
    Comparator.comparing((Person p) -> p.name)
              .thenComparing(p -> p.age);

Use Comparator.comparing(...).thenComparing(...) to express the key sequence directly; Guava ComparisonChain provides a similar fluent alternative. section 7.13

Avoid these comparison mistakes:

  • Handle nullable keys explicitly instead of returning zero merely because one or both values are null. section 7.13
  • Do not return zero when primary keys differ; compare the primary key before the secondary key. section 7.13

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains sequential comparison, contract failures, null handling, and JDK or Guava implementations through focused examples.
Examples
Uses Person name-and-age ordering, secure connections by URL, nullable users, and two-field MyObject comparators.
What it assumes
Assumes familiarity with Java Comparable, Comparator, compareTo, and basic object fields.
What you can do after
Apply Comparator.comparing, thenComparing, ComparisonChain, or explicit key comparisons to implement safer ordering.
How it connects
Connects Comparable, Comparator, lexicographic ordering, null handling, Boolean.compare, and comparator combinators.

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.