java - Generics Collections PECS -
i have question method java.util.collections
:
public class collections { public static <t> void copy(list<? super t> dest, list<? extends t> src) { (int i=0; i<src.size();i++) dest.set(i,src.get(i)); } }
i understand how <? super t>
works, however, don't understand why first parameter list<? super t>
instead of list<t>
. think it's useless in situation. using list<t>
should work well, shouldn't it? give me examples understand if possible, please?
thanks.
no, makes sense. example, consider situation:
t
inputstream
dest
list<object>
src
list<fileinputstream>
that works absolutely fine. of course, could create t
either object
or fileinputstream
in situation - imagine calling from method signature of:
public void dosomething(list<? super inputstream> streams) { // want utilize re-create in here reason }
you don't know it's list<inputstream>
- it's list<? super inputstream>
. if dest
parameter in copy
just list<t>
, we'd stuck... way is written, we're fine.
it makes sense in terms of require destination list - just need able set values of t
within it. likewise require of source list can values of t
it. <? super t>
, <? extends t>
express requirements well.
java
No comments:
Post a Comment