Java Generics and Raw Types

断了今生、忘了曾经 提交于 2020-01-30 05:17:46

问题


I have the next code:

ArrayList value = new ArrayList<Integer>();  // 1
value.add("Test");  // 2

I'm trying to understand line 2. Although I can see that value.add("Test"); compiles without errors, I can't see the reason it doesn't throw a runtime exception. If value is referencing a generic ArrayList object, why Java allows to add a String to it? Can anyone explain it to me?

The closest explanation I've found about this is described here, but I still don't understand the core reason:

Stack s = new Stack<Integer>()

This is a legal conversion from a parameterized type to a raw type. You will be able to push value of any type. However, any such operation will result in an "unchecked call" warning.


回答1:


Generic types are erased during compilation. So at runtime, an ArrayList is a raw ArrayList, no matter if you defined it as generic or not.

In your case, the code compiles as your ArrayList declaration is not generic, and it runs fine because of type erasure.




回答2:


ArrayList value this is your type declaration which is not generic. That is why compiler allows you to add any Object to the list.



来源:https://stackoverflow.com/questions/26733112/java-generics-and-raw-types

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