When you make an ArrayList without specifying the object type, does it create it automatically when you add the first object?

 ̄綄美尐妖づ 提交于 2019-12-18 14:05:26

问题


For example, instead of doing

ArrayList<ClassName> variableName;

you do

ArrayList variableName;

then later you add an object of type "ClassName"

variableName.add(objectName);

will that automatically set the type of your array as

ArrayList<ClassName>

?


回答1:


No. Generics are for compile time only. You are just losing the benefit of that check. At runtime all generic information is erased

In other words,

ArrayList<Type> 

at runtime is just an ArrayList. The benefit of doing that over just a List is that when you are writing your code, the compiler will check that you dont put anything inappropriate in your list.




回答2:


when you don't specify, it would be the same as if you specified ArrayList<Object>, meaning that any type of object could be added to the ArrayList. The type checks which are performed when specifying a class happen at compile time, not at runtime, so its not possible for things to work the way you propose (having them more specific class determined at runtime).




回答3:


The real type is really ArrayList. The ArrayList<ClassName> type only exists for the compiler (this is called erasure), and its purpose is to give type safety at the compiler level. But at the bytecode level you don't have that knowledge of generic types.



来源:https://stackoverflow.com/questions/3936556/when-you-make-an-arraylist-without-specifying-the-object-type-does-it-create-it

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