Exercise Solutions: Interfaces and Polymorphism

Sorting Flavors by Name

Create a Sorting Class

  1. Create a new class called FlavorComparator and have it implement the Comparator interface:

    public class FlavorComparator implements Comparator<Flavor>
    
  2. Always returning 0 results in no sorting, so replace line 8 with:

    return o1.getName().compareTo(o2.getName());
    

    This returns an integer (negative, positive, or zero) depending on whether Flavor object o1 or o2 comes first, alphabetically.

public class FlavorComparator implements Comparator<Flavor> {
   @Override
   public int compare(Flavor flavor1, Flavor flavor2) {
      return flavor1.getName().compareTo(flavor2.getName());
   }
}

Back to the exercises

Sorting Cones by Cost

Now let’s sort our cones list by cost, from least expensive to most expensive.

  1. Create the new class ConeComparator.

  2. Follow the example above to implement the Comparator interface and evaluate Cone objects by cost.

  3. In Main, sort the cones list, then print the elements to the screen to verify the results.

    Before:           After:
    
    Waffle: $1.25        Bowl: $0.05
    Sugar: $0.75         Wafer: $0.50
    Wafer: $0.50         Sugar: $0.75
    Bowl: $0.05          Waffle: $1.25
    
public class ConeComparator implements Comparator<Cone> {
   @Override
   public int compare(Cone cone1, Cone cone2) {
      if (cone1.getCost() - cone2.getCost() < 0){
         return -1;
      } else if (cone1.getCost() - cone2.getCost() > 0) {
         return 1;
      } else {
         return 0;
      }
   }
}

Back to the exercises