Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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 aList
of type<? super T>
with objects of typeT
: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 thestatic <T> void fill(List<? super T> list, T obj)Collections
class (described in the section Algorithms) 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); ... }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.