Declaring an ArrayList and adding objects
suggest changeCreate 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents