09: 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.
For example, on input list ["ear", "za", "cabaret"], the list sorted according to this comparator will be ["za", "ear", "cabaret"]
Hints:
- Start with the class declaration; it should implement
Comparatorwith an appropriate type parameter. - You only have to implement one method.
- Use a method of
Stringto get its length. - You can compare the lengths using
<,>, and/or==correctly, or you can useInteger.compare(examples of each are shown in the notes). - Write this in Eclipse, not MS Word or Google Docs, or you’re gonna have a bad time.