Java Generics: Wildcard capture misunderstanding -


reading java online tutorial haven't understand wildcard capture. example:

    import java.util.list;     public class wildcarderror {      void foo(list<?> i) {       i.set(0, i.get(0));      }     } 

why compiler can't retain assignment safe? knows that,by executing instance, method integer list, gets i.get integer value. try set integer value @ index 0 same integer list (i). so,what's wrong?why write wildcard helper?

why compiler can't retain assignment safe?

the compiler doesn't know anything type of elements in list<?> i, definition of ?. wildcard not mean "any type;" means "some unknown type."

it knows that,by executing instance, method integer list, gets i.get integer value.

that's true, said above: compiler can only know – @ compile time, remember – i.get(0) returns object, upper bound of ?. there's no guarantee ? at runtime object, there no way compiler know i.set(0, i.get(0)) safe call. it's writing this:

list<foo> fooz = /* init */; object foo = fooz.get(0); fooz.set(0, foo); // won't compile because foo object, not foo 

more reading:


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -