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

Defining and Using Generic Methods

Not only types can be parameterized; methods can be parameterized too. Static and non-static methods as well as constructors can have type parameters.

The syntax for declaring method type parameters is the same as the syntax for generics. The type parameter section is delimited by angle brackets and appears before the method's return type. For example the following Collections class method fills a List of type <? super T> with objects of type T:

static <T> void fill(List<? super T> list, T obj) 
Generic methods allow you to use type parameters to express dependencies among the types of one or more arguments to a method or its return type (or both). The type parameters of generic methods generally are independent of any class or interface-level type parameters. The algorithms defined by the Collections class (described in the section Algorithms (in the Learning the Java Language trail)) make abundant use of generic methods.

One difference between generic types and generic methods is that generic methods are invoked like regular methods. The type parameters are inferred from the invocation context, as in this invocation of 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.