Comparing and sorting objects

Giving objects an order: natural ordering with compareTo and the sign of its result, the external comparator, successive criteria, sorting a collection and consistency with equality.

  • 25 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Comparable: what is it?

    Show the answer

    The Java interface whose compareTo method gives a class its natural ordering, used by default to sort its instances.

    a.compareTo(b) returns a negative, zero or positive integer. String and Integer implement it; for our own classes, it is up to us to write implements Comparable<Student>.

  • What is the sign of "pomme".compareTo("poire")?

    • Positive: "pomme" comes after "poire"
    • Negative: "pomme" is shorter
    • Zero: both words start with "po"
    • Negative: "m" comes before "i" in the alphabet
    Show the answer

    Positive: "pomme" comes after "poire"

    The two words differ at the third letter: "m" against "i". "i" comes before "m", so "poire" precedes "pomme" and the result is positive (4, the gap between the codes). Lengths only matter when one word is a prefix of the other.

  • a.compareTo(b) returns a … integer if a comes before b, … if the order does not distinguish them, and a … one if a comes after b.

    Show the answer

    a.compareTo(b) returns a negative integer if a comes before b, zero if the order does not distinguish them, and a positive one if a comes after b.

    Only the sign matters, not the value: "chat".compareTo("chien") is -8, but any negative would mean the same.

  • Comparator: what is it?

    Show the answer

    An external object, separate from the sorted class, that compares two objects and defines an order chosen by the caller.

    Comparator<T> has a method compare(a, b). You can have several orders for the same class (by name, by average), which compareTo alone cannot do.

  • An application must display the same students sometimes sorted by name, sometimes by average. Which design should you choose?

    • Change compareTo before each sort to switch criterion
    • One comparator per criterion, passed to sort according to the choice
    • Duplicate the class: StudentByName and StudentByAverage
    • Sort once, then read the list backwards for the other criterion
    Show the answer

    One comparator per criterion, passed to sort according to the choice

    compareTo defines only one order, fixed in the class. Several orders for the same class is precisely what external comparators are for. Reading backwards does not change the criterion.