Why does following code not throws exception?
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;
}
}
I want to return List<P> instead of List<?> . But when I write List<P> , it means List<Class<P>> . i.e. in above case , it means List<Class<Integer>> , but I want List<Integer> as return.
I want below code: (so that i don’t have to cast again at when method returns)
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;
}
}
This should do the job with minimal fuss: