java - Why cannot I modify collection through up bounded reference but can through its iterator? -


    list<? extends number> list1 = new arraylist<number>(){         {addall(arrays.aslist(1,2,3,4,5));}     };     listiterator  listiterator = list1.listiterator();     listiterator.next();     listiterator.set(999);     system.out.println(list1); 

this code works , outs

[999, 2, 3, 4, 5] 

but if write so:

        list<? extends number> list1 = new arraylist<number>(){             {addall(arrays.aslist(1,2,3,4,5));}         };         list1.set(0,999); 

i see

java: method set in interface java.util.list<e> cannot applied given types;   required: int,capture#1 of ? extends java.lang.number   found: int,int   reason: actual argument int cannot converted capture#1 of ? extends java.lang.number method invocation conversion 

plese clarify behaviour.

p.s. question arisen after watching code

collections.reverse method

public static void reverse(list<?> list) {         int size = list.size();         if (size < reverse_threshold || list instanceof randomaccess) {             (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)                 swap(list, i, j);         } else {             listiterator fwd = list.listiterator();             listiterator rev = list.listiterator(size);             (int i=0, mid=list.size()>>1; i<mid; i++) {                 object tmp = fwd.next();                 fwd.set(rev.previous());                 rev.set(tmp);             }         }     } 

if code example complete, because have dropped generic information listiterator definition. if change include generic info return similar compilation error:

list<? extends number> list1 = new arraylist<number>(){     {addall(arrays.aslist(1,2,3,4,5));} }; listiterator<? extends number>  listiterator = list1.listiterator(); listiterator.next(); listiterator.set(999); system.out.println(list1); 

similarly, if stripped generic definition list add item directly without issue:

    list<? extends number> list1 = new arraylist<number>(){         {addall(arrays.aslist(1,2,3,4,5));}     };     list list2 = list1;     list2.set(0,999); 

this comes down fact generics syntactical sugar aid in compilation, "erased" @ runtime.

http://docs.oracle.com/javase/tutorial/java/generics/erasure.html


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -