Java Reference
In-Depth Information
S
ELF
C
HECK
3.
How would you use the generic
Pair
class to construct a pair of strings
ÐHelloÐ
and
ÐWorldÑ
?
4.
What change was made to the
ListIterator
interface, and why was
that change necessary?
775
776
17.3 Generic Methods
A generic method is a method with a type variable. You can think of it as a template
for a set of methods that differ only by one or more types. One way of defining a
generic method is by starting with a method that operates on a specific type. As an
example, consider the following
print
method:
public class ArrayUtil
{
/**
Prints all elements in an array of strings.
@param a the array to print
*/
public static void print(String[] a)
{
for (String e : a)
System.out.print(e + Ð Ñ);
System.out.println();
}
. . .
}
Generic methods can be defined inside ordinary and generic classes.
This method prints the elements in an array of strings. However, we may want to
print an array of
Rectangle
objects instead. Of course, the same algorithm works
for an array of any type.
Supply the type variables of a generic method between the modifiers and the
method return type.