Java Reference
In-Depth Information
On line 6, if the data type of the argument passed in is
Frame
, the
Frame
is given a
size and displays. Within
main
, line 14 passes in a
String
object, so the
T
is a
String
during that invocation. On line 15, an array of
String
objects is passed in, so
T
is of type
String []
for that invocation. Line 16 passes in a new
Frame
object, so line 6 is
true
and
a 100
100-pixel window displays after line 9 executes. The
ship
method also prints the
toString
method of each argument, so the output to the command prompt is
Shipping a String object
Shipping [Ljava.lang.String;@3e25a5
Shipping java.awt.Frame[frame0,0,0,0x0,invalid,hidden,
layout=java.awt.BorderLayout,title=,resizable,normal]
The Syntax for Invoking a Generic Method
Generics have an optional syntax for specifying the type for a generic method. You can
place the data type of the generic in angle brackets,
<>
, after the dot operator and before
the method call. For example, the following statements are valid method invocations
of the
ship
method in the
Box
class:
Box.<String>ship(“a String object”);
Box.<String []>ship(args);
Box.<Frame>ship(new Frame());
The syntax makes the code more readable and also gives you control over the generic
type in situations where the type might not be obvious.
Let's look at another example of a generic method. Suppose we add the following
method to the
Box
class, which uses the generic
Dish
class discussed earlier in this section:
public static <U> void wrap(List<Dish<U>> list) {
for(Dish<U> dish : list) {
System.out.println(“Wrapping “ + dish);
}
}
The
wrap
method takes in a
List
of
Dish
objects with any data type for the
Dish
's
generic. The
for-each
loop prints out each
Dish<U>
in the list. The following statements
demonstrate invoking the
wrap
method:
Dish<String> d1 = new Dish<String>();
Dish<String> d2 = new Dish<String>();
Dish<String> d3 = new Dish<String>();
List<Dish<String>> dishes = new ArrayList<Dish<String>>();
Search WWH ::
Custom Search