Declaring an ArrayList and adding objects

suggest change

Create an ArrayList through the List interface. The first form is a raw type: the compiler will not check the element type. Prefer a generic form.

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

Now, use the method add to add a String:

aListOfFruits.add("Melon");
aListOfFruits.add("Strawberry");

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

addAll(Collection<? extends E> c) adds every element of another collection:

List<String> aListOfFruitsAndVeggies = new ArrayList<String>();
aListOfFruitsAndVeggies.add("Onion");
aListOfFruitsAndVeggies.addAll(aListOfFruits);

“Onion” is at index 0 in aListOfFruitsAndVeggies, “Melon” at index 1, and “Strawberry” at index 2.

Feedback about page:

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



Table Of Contents