java generics super keyword -
i went through these topics
however, still seem kind of lost super keyword:
when declare collection that:
list<? super number> list = null; list.add(new integer(0));//this compiles list.add(new object());//this doesn't compileshouldn't opposite - have list contains objects (of unknown type) parents of
number.objectshould fit (since parent ofnumber), ,integershouldn't. opposite case reason.provided have following code
static void test(list<? super number> param) { param.add(new integer(2)); } public static void main(string[] args) { arraylist<string> slist = new arraylist<string>(); test(slist); //will never compile, however... }it impossible compile above code (and sanity suggests right behaviour), basic logic prove opposite:
string object, object superclass of number. string should work.i know crazy isn't reason why didn't allow
<s super t>constructs? if yes, why<? super t>allowed?
could me restore missing part of logic chain?
the bounded wildcard in list<? super number> can capture number , of supertypes. since number extends object implements serializable, means types capture-convertible list<? super number> are:
list<number>list<object>list<serializable>
note can add(integer.valueof(0)) of above types. however, can't add(new object()) list<number> or list<serializable>, since violates generic type safety rule.
hence not true can add supertype of number list<? super number>; that's not how bounded wildcard , capture conversion work. don't declare list<? super number> because may want add object (you can't!); because want add number objects (i.e. it's "consumer" of number), , list<number> restrictive.
references
- angelika langer's generics faqs
- what bounded wildcard?
- when use wildcard parameterized type lower bound? ("when concrete parameterized type restrictive.")
- why there no lower bound type parameters? ("because not make sense.")
- jls 5.1.10 capture conversion
see also
- effective java 2nd edition, item 28: use bounded wildcards increase api flexibility
- "pecs stands producer-
extends, consumer-super
- "pecs stands producer-
related questions
- too many list, pecs,
new integer(0)vsvalueof, etc
Comments
Post a Comment