我正在阅读 Joshua Bloch 的 Effective Java 2nd edition,第 25 项(第 122 页)。当您进一步阅读本章时,您会到达作者编写以下代码的地步:
// Naive generic version of reduction - won't compile!
static <E> E reduce(List<E> list, Function<E> f, E initVal) {
E[] snapshot = list.toArray(); // Locks list
E result = initVal;
for (E e : snapshot)
{
result = f.apply(result, e);
}
return result;
}
然后作者声明编译器不会编译它,因为您需要在分配的行中添加显式强制转换E[] snapshot = list.toArray();
,从而导致此E[] snapshot = (E[]) list.toArray();
,然后您会收到一条警告说有[unchecked] unchecked cast
。
Q1:我知道这本书考虑到了 Java 6 的变化(我们现在几乎是 Java 8)。但是,我编写了相同的方法,从编译中得到相同的错误。这是因为我需要添加显式演员表。但是没有警告。那么这个警告是关于什么的呢?
Q2:作者声明以下方法可行,但事实证明它不是类型安全的。
稍加修改,您就可以让它
ClassCastException
在不包含显式转换的行上抛出 a 。
好的,我明白了......但是我怎样才能让它抛出一个ClassCastException
?
如果您想自己检查一下,我会在这篇文章中留下一个准备运行的示例:
import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
List<Integer> ints = Arrays.asList(10,20,30);
Integer result = reduce (ints,new Function<Integer>() {
@Override
public Integer apply(Integer arg1, Integer arg2)
{
return arg1 + arg2;
}
},0);
System.out.println(result);
}
static <E> E reduce(List<E> list, Function<E> f, E initVal)
{
E[] snapshot = (E[]) list.toArray(); // Locks list
E result = initVal;
for (E e : snapshot)
{
result = f.apply(result, e);
}
return result;
}
interface Function<T>
{
public T apply(T arg1, T arg2);
}
}