This is not a completely new answer, more of a sum-up of what's already said.
With the Java Collections Framework, as the type parameter (in the angle brackets) you name what type of objects you want to store in the Collection (List
, Set
, ...).
By the language design, you cannot use primitive types like int
, long
, double
etc. there, only reference types. So, if you want to store integers in an ArrayList
, you have to do ArrayList<Integer>
instead of ArrayList<int>
.
But later in your code, you want to add Strings to your list. To allow that, your list should be declared ArrayList<String>
. An ArrayList<Integer>
will give a compile error when trying to add anything that is not an Integer
.
You can of course declare an ArrayList<Object>
. That one will accept all types of objects (String
, Integer
, Person
, File
, ...), but that's against the idea behind generics: to tell the compiler as specifically as possible what type of objects you want to allow in your list (and disallow the others), avoiding strange runtime errors.
And it's good style to declare something like
List<String> names = new ArrayList<>();
or
Collection<String> names = new ArrayList<>();
If later you decide that a LinkedList
or a HashSet
is the data structure that better suits your program's need, then you just change the right-hand side of the declaration.