我正在阅读 J. Bloch 的《Effective Java》书籍,现在正处于数组 vs 列表的部分。以下是他提供的未经检查的转换示例:
interface Function<T> {
T apply(T arg1, T arg2);
}
public class Main{
public static void main( String[] args ){
Function<String> f = null;
List<String> str = Arrays.asList("asd");
//staff
reduce(str, f, ""); //E's deduced to String. Where is type-unsafe?
}
static <E> E reduce(List<E> list, Function<E> f, E initVal) {
E[] snapshot = (E[]) list.toArray(); // Unchecked cast
E result = initVal;
for (E e : snapshot)
result = f.apply(result, e);
return result;
}
}
他说这种方法不是类型安全的,我们很容易遇到ClassCastException异常。但我并不明白为什么会这样。哪里不安全了?类型变量E将始终被推导为适当的类型,因此我们不必担心ClassCastException异常。
你能否举个抛出ClassCastException异常的例子吗?