java - problems invoking a method with a generic type argument -
i have problem generics, let me explain.
i have class wraps linkedlist:
public class idnlist<t extends numerable> extends idnelement implements list<t> { private linkedlist<t> linkedlist; @override public boolean add(t e){ return linkedlist.add(e); } //stuff }
please note generic type t
of class extends
numerable
interface.
ok, inside different class want invoke method follows:
if(childtoadd instanceof numerable) ((idnlist<?>)this).add((numerable)childtoadd);
but eclipse says: the method add(capture#1-of ?) in type idnlist<capture#1-of ?> not applicable arguments (numerable)
, , can't figure out why can't work. why can't add numerable
object list? missing?
edit: it's classic. ask, , find clue. seems workaround is:
((idnlist<numerable>)this).add((numerable)childtoadd);
but don't know how elegant is. appreciate further comments.
say have classes a
, b
both extend numerable
. there 3 valid types of idnlist
: idnlist<a>
, idnlist<b>
, , idnlist<numerable>
.
i hope agree shouldn't able add numerable
idnlist<a>
.
now, in line of code, how compiler know whether you've matched types correctly?
(idnlist<?>)this).add((numerable)childtoadd);
all knows childtoadd
numerable
, , this
kind of idnlist
. doesn't know kind, can't guarantee type safety. remember generic type checking done entirely @ compile time, not runtime.
i see how workaround allows code compile, i'm not sure risks of are. seems me since generic type parameters erased @ runtime, you're bypassing type checking here.
Comments
Post a Comment