----------- lasted update ---------
I think maybe List<?>
and List<E>
are the same type when we declare them as a method argument. I tried to convert List<E>
to List<?>
, it worked fine too:
public static <E> void swap2(List<E> list, int i, int j){
swapHelper2(list, i ,j);
}
private static void swapHelper2(List<?> list, int i, int j) {
...
}
------------ original question ------------
From 《Effective Java》 Item 31 it says:
The idea is to write a private helper method to capture the wildcard type...
'private helper method':
public static void swap(List<?> list, int i, int j) {
swapHelper(list, i, j);
}
// Private helper method for wildcard capture
private static <E> void swapHelper(List<E> list, int i, int j) {
list.set(i, list.set(j, list.get(i)));
}
My question is why List<?> could convert to List<E> through method invocation without compile error?
In my opinion I think List<?> is a SuperType of any List<E>, so it should need some narrowing conversion such as:
List<?> list = new ArrayList<>();
List<String> listOfString = (List<String>)list;
swapHelper(listOfString, 0 ,0);