为什么下面的代码不会抛出异常?
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unchecked")
public class MainRunner {
public static void main(String[] args) {
List<String> s = new ArrayList<String>() {
{
add("a");
add("1");
add("1");
}
};
// List<Integer> i = (List<Integer>) listConvertor(s, new Integer("1"));
List<Integer> i = (List<Integer>) listConvertor(s, Integer.class);
System.out.println(i);
}
@SuppressWarnings("unchecked")
public static <T, P> List<?> listConvertor(List<T> inputList, P outputClass) {
List<P> outputList = new ArrayList<P>(inputList.size());
for (T t : inputList) {
outputList.add((P) t); // shouldn't be classCastException here?
}
return outputList;
}
}
我想返回List<P>
而不是List<?>
. 但是当我写的时候List<P>
,它的意思是List<Class<P>>
。即在上述情况下,这意味着List<Class<Integer>>
,但我想List<Integer>
作为回报。
我想要下面的代码:(这样我就不必在方法返回时再次转换)
List<Integer> i = listConvertor(s, Integer.class);
System.out.println(i);
}
@SuppressWarnings("unchecked")
public static <T, P> List<P> listConvertor(List<T> inputList, P outputClass) {
List<P> outputList = new ArrayList<P>(inputList.size());
for (T t : inputList) {
outputList.add((P) t); // shouldn't be classCastException here?
}
return outputList;
}
}