In this tutorials, we will see how to add elements to ArrayList.

add elements to ArrayList :

ArrayList class gave us add() method to add elements into ArrayList.

Syntax :

public boolean add(Object obj);

According to the Oracle Docs, add() method appends the specified element to the end of this list.

add() Example :

import java.util.ArrayList;

public class AddElement {
    public static void main(String args[]) {
        ArrayList<String> fruitsList = new ArrayList();
        fruitsList.add("Banana");
        fruitsList.add("Apple");
        fruitsList.add("Grapes");
        fruitsList.add("Mango");

        fruitsList.forEach((fruit)->System.out.println(fruit));

        System.out.println("=================");

        ArrayList<Double> data = new ArrayList();
        data.add(0.56);
        data.add(2.5);
        data.add(1.2);
        data.add(0.75);

        data.forEach((item)->System.out.println(item));

    }
}

Output :

Banana
Apple
Grapes
Mango
=================
0.56
2.5
1.2
0.75

ArrayList add() elements at a specific index :

As we seen above, when we add elements into ArrayList, by default the elements will be appended to the end of this list.

As ArrayList is index based collection, we can add an element at a specific index position.

To add an element at a specific index, we can use add(index pos,Object element) overloaded method.

According to Oracle Docs : Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Example :

import java.util.ArrayList;

public class Sample {
    public static void main(String args[]) {
        ArrayList<String> fruitsList = new ArrayList();
        fruitsList.add("Banana");
        fruitsList.add("Apple");
        fruitsList.add("Grapes");
        fruitsList.add("Mango");

        fruitsList.forEach((fruit)->System.out.println(fruit));

        // Adding Element at a specific 1st position.
        fruitsList.add(1,"Gua");
        System.out.println("After Adding Element at 1st position :");
        System.out.println("======================================");
        fruitsList.forEach((fruit)->System.out.println(fruit));

    }
}

Output :

Banana
Apple
Grapes
Mango
After Adding Element at 1st position :
======================================
Banana
Gua
Apple
Grapes
Mango

 

Reference :

How ArrayList works internally

Ways to create arraylist in java

Happy Learning 🙂