08: Writing Comparators

Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.


In class, we had PostalAddress implement the Comparable interface and wrote a compareTo method to give it a natural order. Sometimes we want to define additional orderings on a class, and so we define a new Comparator class for each such ordering. (See the notes for an examples of using a “postal sort”).

(2 points) Define a Comparator for Strings such that a sort call on a List<String> of strings sorts the strings by length, shortest to longest. Show the entire class definition.

Hints:

  • Start with the class declaration; it should be of type Comparator with an appropriate type parameter.
  • You only have to implement one method.
  • Use a method of String to get its length.
  • You can compare the lengths using <, >, and == correctly, or you can use Integer.compare (examples of each are shown in the notes).