Java Reference
In-Depth Information
youcanonlypassanargumentof
List<Object>
type,whichlimitstheusefulnessof
this method.
However, generics offer a solution: the wildcard argument (
?
), which stands for
any type. By changing
outputList()
's parameter type from
List<Object>
to
List<?>
, you can call
outputList()
with a
List
of
String
, a
List
of
Em-
ployee
, and so on.
Generic Methods
Suppose you need a method to copy a
List
of any kind of object to another
List
.
Although you might consider coding a
void copyList(List<Object> src,
List<Object> dest)
method,thismethodwouldhavelimitedusefulnessbecause
itcouldonlycopylistswhoseelementtypeis
Object
.Youcouldn'tcopya
List<Em-
ployee>
, for example.
If you want to pass source and destination lists whose elements are of arbitrary
type (but their element types agree), you need to specify the wildcard character as
a placeholder for that type. For example, you might consider writing the following
copyList()
classmethodthatacceptscollectionsofarbitrary-typedobjectsasitsar-
guments:
static void copyList(List<?> src, List<?> dest)
{
for (int i = 0; i < src.size(); i++)
dest.add(src.get(i));
}
Thismethod'sparameterlistiscorrect,butthereisanotherproblem:thecompilerout-
puts the following error message when it encounters
dest.add(src.get(i));
:
CopyList.java:18: error: no suitable method found for
add(Object)
dest.add(src.get(i));
^
method List.add(int,CAP#1) is not applicable
(actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
(actual argument Object cannot be converted to CAP#1
by method invocation conversion)
where CAP#1 is a fresh type-variable: