How to Create an ArrayList and Add Elements to It

This example demonstrates how to create ArrayList and add new elements to it.

Create an ArrayList and Adding New Elements to It

  • How to create an ArrayList using the ArrayList() constructor.
  • Add new elements to an ArrayList using the add() method.
import java.util.ArrayList;
import java.util.List;

public class CreateArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        List<String> animals = new ArrayList<>();

        // Adding new elements to the ArrayList
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals);

        // Adding an element at a particular index in an ArrayList
        animals.add(2, "Elephant");

        System.out.println(animals);
    }
}

Output

[Lion, Tiger, Cat, Dog]
[Lion, Tiger, Elephant, Cat, Dog]

Reference

Comments