09: 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:

  • Start with the class declaration; StringACountComparator should implement Comparator with an appropriate type parameter (<String>) – just like the PostalAddressComparator implemented Comparator with type PostalAddress.
  • You only have to implement one method. The simpler and clearer, the better.
  • Use a method of String to retrieve the characters. Then count the occurrences of a.
  • You can compare the counts using <, >, and/or == correctly, or you can use Integer.compare (we did both in class).
  • Write this class in Eclipse, not MS Word or Google Docs, or you’re gonna have a bad time.

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 follow set theoretic expressions, is the value returned by the corresponding Java expression equivalent? 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 s.retainAll(t)

D. T \ S and t.removeAll(s)