次のコードが例外をスローしないのはなぜですか?
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;
}
}