Wednesday, 15 April 2015

wildcard - Confusion over Java generic method type inference -



wildcard - Confusion over Java generic method type inference -

the sample method given below:

static <t> void dosomething(list<? super t> list1, list<? extends t> list2) { }

i wondering type inferred in situation , logic. let's calling method this:

dosomething(new arraylist<object>(), new arraylist<string>());

would t type evaluate object or string?

this phone call not bind t specific class. java not need know exact t because of type erasure implementation of generics. long types pass consistent declaration, code should compile; in case, lists of object , string consistent declaration.

let's expand code little forcefulness binding of t specific type. perhaps easiest way pass class<t>, this:

static <t> void dosomething(list<? super t> list1, list<? extends t> list2, class<t> cl) { system.out.println(cl); }

now allow seek calling dosomething string.class , object.class:

dosomething(new arraylist<object>(), new arraylist<string>(), object.class); dosomething(new arraylist<object>(), new arraylist<string>(), string.class);

both calls compile, producing output

class java.lang.object class java.lang.string

demo on ideone.

java wildcard type-inference generic-type-argument

No comments:

Post a Comment