Assignment 9: Generics
Goals: Practice working with generic lists and functions.
You should submit one .java file containing the solution to this problem.
Be sure to properly test your code and write purpose statements for your methods. A lack of tests and documentation will result in a lower grade! Remember that testing requires you to make some examples of data in an examples class.
Generics Lists
Design the classes and interfaces necessary to represent a generic list.
Using these classes, construct examples of lists of strings and lists of integers.
Design a method which appends one list to another. Optional: Design this with foldr in an abstract class.
Argmax (& Argmin)
// generic function interface IFunc<X, Y> { Y apply(X input); } // extracts the value of an input interface IEvaluator<X> extends IFunc<X, Integer> {}
Design a method argmax on a list, which takes an evaluator and produces the element with the highest value. This method should break ties by selecting the element which appears earlier in the list and should throw an UnsupportedOperationException if it is ever called on an empty list. The value of an element should never be measured more than once.
Use argmax to retrieve the biggest number in a list of integers and the longest string in a list of strings.
Optional: Design argmin and abstract the two methods so any shared logic is not duplicated, using an abstract class as appropriate.
Sorting
// compares two values interface IComparator<X> { // returns a negative number if x1 is "smaller" than x2 // returns 0 if they are considered equal // returns a positive number if x1 is "bigger" than x2 int compare(X x1, X x2); }
Design a method which sorts a list based on a comparator, with the "smallest" element being first. Hint: You will need a helper method that inserts a new element into an already-sorted list, and be sure to only call this helper on a list that has been sorted (via recursion!).
Use this method to sort a list of strings alphabetically and a list of strings by length. Hint: Recall the compareTo method on strings.
Design a comparator which uses an evaluator to determine what is and isn’t smaller. Write a test which will demonstrate that this new kind of comparator can behave equivalentally to one you have already defined.