Java Add Element to ArrayList

Tags: ArrayList

In this Java core tutorial we learn how to add one element or multiple elements to an java.util.ArrayList in Java programming language.

Table of contents

  1. How to add one element to ArrayList in Java
  2. How to add multiple elements to ArrayList in Java

How to add one element to ArrayList in Java

In Java, with a given ArrayList object we can use the List.add(E e) method to add an element to the ArrayList as the following example Java code.

AddElementToArrayListExample1.java

import java.util.ArrayList;
import java.util.List;

public class AddElementToArrayListExample1 {
    public static void main(String... args) {
        List<String> list = new ArrayList<>();

        list.add("One");
        list.add("Two");
        list.add("Three");

        System.out.println("ArrayList: " + list);
    }
}
The output as below.
ArrayList: [One, Two, Three]

How to add multiple elements to ArrayList in Java

In Java, we can use the List.addAll(Collection<? extends E> c) method to add all elements of a collection to another one.

In the following example Java program, we show how to add all elements of an ArrayList object to another ArrayList object using the addAll() method above.

AddElementToArrayListExample2.java

import java.util.ArrayList;
import java.util.List;

public class AddElementToArrayListExample2 {
    public static void main(String... args) {
        List<String> list1 = new ArrayList<>();
        list1.add("One");
        list1.add("Two");

        List<String> list2 = new ArrayList<>();
        list2.add("Three");
        list2.add("Four");
        list2.add("Five");

        // Add all element from list2 to list1
        list1.addAll(list2);

        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
    }
}
The output as below.
list1: [One, Two, Three, Four, Five]
list2: [Three, Four, Five]

Happy Coding 😊

Java Convert Array to ArrayList

Java Insert Element to ArrayList at Specified Index

Java Get Minimum Value in ArrayList

How to Traverse ArrayList using Iterator in Java

How to Traverse ArrayList using for each loop in Java

How to Traverse ArrayList using forEach() method in Java

Java Convert ArrayList to LinkedList

Java Convert ArrayList to Array

Java Convert ArrayList to String

Java Convert ArrayList to Comma Separated String

Java Convert ArrayList to HashSet

Convert Array to List in Java

Java Create New Array with Class Type and Length

Java Create ArrayList using List Interface

Java Get Index of Minimum Value in ArrayList

How to use Java ArrayList with Examples