Declaring an ArrayList and adding objects

suggest change

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

List aListOfFruits = new ArrayList();
List<String> aListOfFruits = new ArrayList<String>();
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.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents