问题
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