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
:
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.
Also we can add multiple elements with addAll(Collection<? extends E> c)
method
List<String> aListOfFruitsAndVeggies = new ArrayList<String>();
aListOfFruitsAndVeggies.add("Onion");
aListOfFruitsAndVeggies.addAll(aListOfFruits);
Now "Onion" is placed at 0 index in aListOfFruitsAndVeggies
, "Melon" is at index 1 and "Strawberry" is at index 2.