How to Create an ArrayList and Add Elements to It

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

Example 1: Steps to Create an ArrayList and Add Elements to it in Java

To create an ArrayList and add elements to it in Java, you can follow these steps:

Import the necessary package:

import java.util.ArrayList;

Declare an ArrayList variable:

ArrayList<String> myList = new ArrayList<>();

Replace String with the desired data type if you're working with a different type of element.

Add elements to the ArrayList using the add() method:

myList.add("Element 1");
myList.add("Element 2");
myList.add("Element 3");

You can add as many elements as needed.

Access and manipulate the elements in the ArrayList:

System.out.println(myList.get(0)); // Output: Element 1
myList.set(1, "Modified Element 2");

In the example above, get(0) retrieves the element at index 0, and set(1, "Modified Element 2") modifies the element at index 1.

Here's the complete example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> myList = new ArrayList<>();

        myList.add("Element 1");
        myList.add("Element 2");
        myList.add("Element 3");

        System.out.println(myList.get(0)); // Output: Element 1

        myList.set(1, "Modified Element 2");
        System.out.println(myList.get(1)); // Output: Modified Element 2
    }
}

Note: Remember to specify the correct data type when declaring the ArrayList, based on the type of elements you want to store.

Example 2: 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

Java ArrayList Source Code Examples


Comments