Homework 10: Comparators and Sets

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 StringACountComparator for String such that a sort call on a List<String> of Strings sorts them by the number of times the lowercase character a occurs, in ascending order (least to greatest). Show the entire class definition.

For example, on input list ["Angela", "aardvark", "bird"], the list sorted according to this comparator will be ["bird", "Angela", "aardvark"]

Hints:


Suppose we have sets of integers S and T, and we have corresponding Java objects of type Set<Integer> named s and t. For each of the following expressions, are the values equal? You’ll probably want to read the Java API’s description of each method. Explain your answer in a single sentence. The key thing to consider is whether the expression defines a value (either a boolean or a new set) or modifies a value. (1 point each)

A. 6 ∈ T and t.contains(6)

B. T ⊆ S and s.containsAll(t)

C. S ∩ T and the contents of s after calling s.retainAll(t)

D. T \ S and the contents of t after calling t.removeAll(s)