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 automatical开发者_运维技巧ly set the type of your array as
ArrayList<ClassName>
?
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.
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).
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.
精彩评论