Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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:A type parameter is used to express dependencies between:static <T> boolean myMethod(List<? extends T>, T obj)Static methods, non-static methods, and constructors can all have type parameters.
- the types of the method's arguments
- the type of the method's argument and the method's return type
- both
For example, the
fill
method in theCollections
class has a dependency between its two arguments:The type parameter is used to show that the second argument, of typestatic <T> void fill(List<? super T> list, T obj)
T
, is related to the first argument, aList
that contains objects of typeT
or objects of a supertype ofT
. For more examples, the algorithms defined by theCollections
class (described in the Algorithms 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); ... }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.