generics - I am having some wrong concept about wildcard in Java -


i trying understand how use wildcard in java.

import java.util.list; public class wildcarderror{     void foo(list<?> i){         i.set(0, i.get(0));     } }  public class wildcardfixed{     void foo(list<?> i){         foohelper(i);     }     private <t> void foohelper(list<t> l){         l.set(0, l.get(0));     } } 
  • why first class cannot compiled whereas second 1 can?
  • what happen when compiler sees wildcard? turns object? void foo(object i) in first class, or void foo(list<object> i).
  • how type inference works in second class ?

when this:

import java.util.arraylist; import java.util.list;  public class wildcard {      public static void main(string[] args) {     wildcardfixed wf = new wildcardfixed();     list<integer> li = new arraylist<>();     li.add(0);     wf.foo(li);     system.out.println("success");     } }  class wildcarderror{     void foo(list<?> i){         i.set(0, i.get(0));     } }  class wildcardfixed{     void foo(list<?> i){         foohelper(i);     }     private <t> void foohelper(list<t> l){         l.set(0, l.get(0));     } } 

the wildcarderror class fails compile message

the method set(int, capture#1-of ?) in type list not applicable arguments (int, capture#2-of ?)

in plainer english, compiler saying doesn't know type of thing contained in i, i.e. doesn't know type returned get(), , doesn't know type of argument set() takes, can't guarantee set() operation succeed.

wildcardfixed, however, compiles because reassure compiler that, whatever type in l, result of get same type, t, argument type of set. compiler doesn't need go on, needs more ?.

you can simpler, though. if put type parameter t original foo() method, compiles , runs perfectly.

import java.util.arraylist; import java.util.list;  public class wildcard {      public static void main(string[] args) {     wildcardfixed wf = new wildcardfixed();     list<integer> li = new arraylist<>();     li.add(0);     wf.foo(li);     system.out.println("success wildcardfixed");      wildcardwitht wt = new wildcardwitht();     wt.foo(li);     system.out.println("success wildcardwitht");     } }  class wildcarderror{     void foo(list<?> i){         i.set(0, i.get(0));     } }  class wildcardfixed{     void foo(list<?> i){         foohelper(i);     }     private <t> void foohelper(list<t> l){         l.set(0, l.get(0));     } }  class wildcardwitht {     <t> void foo(list<t> i) {     i.set(0, i.get(0));     } } 

Comments