本文介绍了为什么要编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我今天早些时候被调试一些代码,发现像下面的东西不会引发编译时异常:
I was taken aback earlier today when debugging some code to find that something like the following does not throw a compile-time exception:
public Test () {
HashMap map = (HashMap) getList();
}
private List getList(){
return new ArrayList();
}
您可以想象, ClassCastException
在运行时抛出,但是有人可以解释为什么将 List
转换为 HashMap
因为可以想象 getList()
可能是在编译时合法的?
As you can imagine, a ClassCastException
is thrown at runtime, but can someone explain why the casting of a List
to a HashMap
is considered legal at compile time?
推荐答案
返回 HashMap
的子类,它也实现了 List
。不太可能,是的,但可能的,因此可编译。
Because conceivably getList()
could be returning a subclass of HashMap
which also implements List
. Unlikely, yes, but possible, and therefore compilable.
这篇关于为什么要编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!