Java Reference
In-Depth Information
Atypeparameter'sscopeisitsgenerictypeexceptwheremasked.Thisscopeincludes
the formal type parameter list of which the type parameter is a member.
Topreservetypesafety,youarenotallowedtoviolatethefundamentalruleofgeneric
types: for a given subtype x of type y , and given G as a raw type declaration, G<x>
is not a subtype of G<y> .Inotherwords,multipleparameterizedtypesthatdifferonly
inregardtoonetypeparameterbeingasubtypeofanothertypeparameterarenotpoly-
morphic.Forexample, List<String> isnotaspecializedkindof List<Object> .
Thisrestrictioncanbenamelioratedwithoutviolatingtypesafetybyusingwildcards.
For example, where a void output(List<Object> list) method can only
outputa List thatcontains Object s(toadheretotheaforementionedrule),a void
output(List<?> list) method can output a List of arbitrary objects.
Wildcardsalonecannotsolvetheproblemwhereyouwanttocopyone List toan-
other.Thesolutionistouseagenericmethod,a static oron- static methodwitha
type-generalizedimplementation.Forexample,a <T> void copyList(List<T>
src, List<T> dest) methodcancopyasource List ofarbitraryobjects(whose
typeisspecifiedby T )toanother List ofarbitraryobjects(havingthesametype).The
compiler infers the actual type arguments from the context in which the method is in-
voked.
Reification is representing the abstract as if it was concrete -- for example, making
amemoryaddressavailablefordirectmanipulationbyotherlanguageconstructs.Java
arraysarereifiedinthatthey'reawareoftheirelementtypes(anelementtypeisstored
internally) and can enforce these types at runtime. Attempting to store an invalid ele-
ment in an array causes the JVM to throw an instance of the ArrayStoreExcep-
tion class.
Unlikewitharrays,agenerictype'stypeparametersarenotreified.They'renotavail-
able at runtime because they're thrown away after the source code is compiled. This
“throwingawayoftypeparameters”isaresultoferasure,whichalsoinvolvesinserting
caststoappropriatetypeswhenthecodeisn'ttypecorrect,andreplacingtypeparamet-
ers by their upper bounds (such as Object ).
When you invoke a varargs method whose parameter is declared to be a parameter-
izedtype(asin List<String> ),thecompileremitsawarningmessageatthepointof
call.Thismessagecanbeconfusingandtendstodiscouragetheuseofvarargsinthird-
party APIs.
Thewarningmessageisrelatedtoheappollution,whichoccurswhenavariableofa
parameterized type refers to an object that is not of that parameterized type.
Search WWH ::




Custom Search