Practice: Contraint Typing

Practice: Contraint Typing#

Question #1: Write the prototype for a generic static method answer1 that accepts a List where the objects in the list are guaranteed to be an instancof Node. Have the method return a void.

Question #2: Update this prototype so that the body of the method will work. Note that the method compareTo belongs to the Comparable interface.

public static <T> int reverseCompare(T o1, T o2) {
    return o2.compareTo(o1);
}  

Question #3: Update this prototype so that it is a proper generic that will process a list of any type of Animal (e.g. List<Cat>).

public void processAnimals(List list) {
    for (Animal animal : list) {
        System.out.println(animal);
    }
}

Question #x: This question does not make use of any Constraints… yet. It is a warm up to the next problem.

Write the prototype for a generic instance method of a generic class with <T> defined. The method will be named answer. The method will accept two arguments:

  • A Comparator interface named comparator. The compare method will compare objects of type U.

  • A Function interface named extractor. The function will take an object of type T. It will return an object of type U.

public class Example<T> {
    // prototype for answer
}

Question #y: This is an extension to the above question where we now add constraints.

Write the prototype for a generic instance method of a generic class with <T> defined. The method will be named answerMe. The method will accept two arguments:

  • A Comparator interface named comparator. The compare method will compare any type that is a supertype of a new generic type U.

  • A Function interface named extractor. The function will take any type that is a supertype of T. It will return any type that is a subtype of U.

public class Example<T> {
    // prototype for answerMe
}