views:

57

answers:

3

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>

?

+6  A: 

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.

hvgotcodes
+3  A: 

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).

stew
I would say that semantically ArrayList<Object> means "this list holds objects of potentially any type", while ArrayList means "this is either legacy code or I didn't bother to specify the type of this list's elements to the compiler".
ninjalj
ninjalj: Then what would you call ArrayList<?> ? I would call that "this list holds objects of potentially any type", while an ArrayList<Object> would be "this holds objects"..
bwawok
+1  A: 

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.

ninjalj