Java Reference
In-Depth Information
CAP#1 extends Object from capture of ?
1 error
Thiserrormessageassumesthat
copyList()
ispartofaclassnamed
CopyList
.
Although it appears to be incomprehensible, the message basically means that the
dest.add(src.get(i))
method call violates type safety. Because
?
implies that
anytypeofobjectcanserveasalist'selementtype,it'spossiblethatthedestinationlist's
element type is incompatible with the source list's element type.
Forexample,supposeyoucreatea
List
of
String
asthesourcelistanda
List
of
Employee
asthedestinationlist.Attemptingtoaddthesourcelist's
String
elements
tothedestinationlist,whichexpects
Employee
s,violatestypesafety.Ifthiscopyop-
erationwereallowed,a
ClassCastException
instancewouldbethrownwhentry-
ing to obtain the destination list's elements.
You could avoid this problem by specifying
void copyList(List<String>
src, List<String> dest)
, but this method header limits you to copying only
listsof
String
objects.Alternatively,youmightrestrictthewildcardargument,which
is demonstrated here:
static void copyList(List<? extends String> src,
List<? super String> dest)
{
for (int i = 0; i < src.size(); i++)
dest.add(src.get(i));
}
Thismethoddemonstratesafeatureofthewildcardargument:Youcansupplyanup-
per bound or (unlike with a type parameter) a lower bound to limit the types that can
bepassedasactualtypeargumentstothegenerictype.Specifyanupperboundvia
ex-
tends
followed by the upper bound type after the
?
, and a lower bound via
super
followed by the lower bound type after the
?
.
You interpret
? extends String
to mean that any actual type argument that
is
String
or a subclass can be passed, and you interpret
? super String
to
implythatanyactualtypeargumentthatis
String
orasuperclasscanbepassed.Be-
cause
String
cannotbesubclassed,thismeansthatyoucanonlypasssourcelistsof
String
and destination lists of
String
or
Object
.
The problem of copying lists of arbitrary element types to other lists can be solved
throughtheuseofa
generic method
(aclassorinstancemethodwithatype-generalized
implementation). Generic methods are syntactically expressed as follows: