I read the following section in a Java tutorial: http://docs.oracle.com/javase/tutorial/java/generics/capture.html
This starts with the following code causing an error due to the fact that the capture cannot be converted to an object, so the set method cannot confirm that the object has capture type # 1:
import java.util.List; public class WildcardError { void foo(List<?> i) { i.set(0, i.get(0)); } }
I somewhat understand the reasons for this. i.get returns an object, and the compiler cannot determine whether the object is capture type # 1, so it cannot match it with the second argument as a file.
Then it is recommended that you use the following code to run this method:
public class WildcardFixed { void foo(List<?> i) { fooHelper(i); }
I understand a little why this code works, in this code l.get guaranteed to be of type T, so it can be passed as an argument of type T.
I do not understand why you could not just use a method like this without an assistant:
class GenericsTest { static <K> void bar(List<K> l) { l.set(0, l.get(l.size() - 1)); } public static void main(String[] args) { List<Integer> lst = Arrays.asList(1, 2, 3, 4); bar(lst); System.out.println(lst);
i.e. if you're going to use type inference, why not just use explicitly typed template generalizations and a helper function? Is there any advantage when using wildcards in this scenario? In which cases would you prefer to use a wildcard for a typed generic?
source share