假设我知道List<Base>
只包含Derived
类型的元素,如何强制转换为List<Derived>
?
答案 0 :(得分:1)
我的解决方案:
public static <T> List<T>
cast(List<? super T> list, Class<T> clazz) {
if( list.stream().allMatch( clazz::isInstance ) )
return (List<T>) list;
else
throw new IllegalArgumentException ("Not all inputs are of class " + clazz.getName());
}
答案 1 :(得分:0)
public static void main(String[] args) {
List<Number> foo = new ArrayList<>();
List<Integer> a = cast(foo);
System.out.println("a = " + a);
}
public static <T, C extends T> List<C> cast( List<T> l ) {
return (List<C>) l;
}