The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Using Generic Methods

Not only types can be parameterized; methods can be parameterized too. A generic method defines one or more type parameters in the method signature, before the return type:
static <T> boolean myMethod(List<? extends T>, T obj)
A type parameter is used to express dependencies between: Static methods, non-static methods, and constructors can all have type parameters.

For example, the fill method in the Collections class has a dependency between its two arguments:

static <T> void fill(List<? super T> list, T obj)  (in the API reference documentation)
The type parameter is used to show that the second argument, of type T, is related to the first argument, a List that contains objects of type T or objects of a supertype of T. For more examples, the algorithms defined by the Collections class (described in the Algorithms (in the Learning the Java Language trail) section) make abundant use of generic methods.

One difference between generic types and generic methods is that generic methods are usually invoked like regular methods. The type parameters are inferred from the invocation context, as in this example that calls the fill method:

public static void main(String[] args) {
    List<String> list = new ArrayList<String>(10);
    for (int i = 0; i < 10; i++) {
        list.add("");
    }
    String filler = args[0];
    Collections.fill(list, filler);
    ...
}

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.