Java Language Collections Declaring an ArrayList and adding objects


We can create an ArrayList (following the List interface):

List aListOfFruits = new ArrayList();
Java SE 5
List<String> aListOfFruits = new ArrayList<String>();
Java SE 7
List<String> aListOfFruits = new ArrayList<>();

Now, use the method add to add a String:


In the above example, the ArrayList will contain the String "Melon" at index 0 and the String "Strawberry" at index 1.

Also we can add multiple elements with addAll(Collection<? extends E> c) method

List<String> aListOfFruitsAndVeggies = new ArrayList<String>();

Now "Onion" is placed at 0 index in aListOfFruitsAndVeggies, "Melon" is at index 1 and "Strawberry" is at index 2.