Why does this compile?

ぃ、小莉子 提交于 2019-12-21 06:58:31

问题


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();
 }

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?


回答1:


Because conceivably getList() could be returning a subclass of HashMap which also implements List. Unlikely, yes, but possible, and therefore compilable.




回答2:


For one thing List is an interface. There is no reason why there couldn't exist a subclass of HashMap which also implements the List interface. In this situation it would be perfectly valid.



来源:https://stackoverflow.com/questions/1495308/why-does-this-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!