Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 

?

like image 272
trusktr Avatar asked Oct 14 '10 18:10

trusktr


People also ask

Does an ArrayList object grows automatically as elements are added?

As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

Can you declare an ArrayList without type?

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.

Does ArrayList guarantee insertion order?

ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection.


1 Answers

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.

like image 124
hvgotcodes Avatar answered Oct 23 '22 11:10

hvgotcodes