java generics super keyword -


i went through these topics

however, still seem kind of lost super keyword:

  1. when declare collection that:

    list<? super number> list = null; list.add(new integer(0));//this compiles list.add(new object());//this doesn't compile 

    shouldn't opposite - have list contains objects (of unknown type) parents of number. object should fit (since parent of number), , integer shouldn't. opposite case reason.

  2. 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

see also

  • effective java 2nd edition, item 28: use bounded wildcards increase api flexibility
    • "pecs stands producer-extends, consumer-super

related questions

  • too many list, pecs, new integer(0) vs valueof, etc

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -