Wildcard Parameters and Generic Methods

The final piece of generics relates to the interaction between generic type parameters and methods. Most of the generic features we have seen so far are intended for API and library programmers. The main thing regular programmers need to remember is that:

public class HashSet <E> { /*more code*/

means that (to use this class) you will declare and instantiate a HashSet to work with a specific type:

HashSet<Timestamp> ht = new HashSet<Timestamp>();

The generic features presented in this section are different. These features are intended for use by regular programmers. You'll need these features in your own code, when you use somebody else's generic class.

There are two main generic-related features we are going to cover. Both of them concern methods and generics. The two features are:

  • Expressing various bounds on a generic that is used as a method parameter. Here's an example method signature with a generic parameter:

    static void shuffle(List<Double> list)

    We need a way to get rid of that too-detailed <Double> and express “this method can work with a List of <AnyType> or <AnySubclassOf T> or <AnySuperclassOf T>”.

  • Parameterizing a method, (rather than a class or interface) with a generic parameter. From our experience with generic classes, we would expect to write a generic method something like this:

    static <genericParam> void sort(List<genericParam> list)

We'll cover these new features in this order in the next two major sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.183.138