Java ArrayList addAll() Method

The ArrayList.addAll() method in Java is used to add all elements from a specified collection to the ArrayList. This guide will cover the usage of this method, explain how it works, and provide examples, including a real-world use case to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. addAll(Collection<? extends E> c) Method Syntax
  3. addAll(int index, Collection<? extends E> c) Method Syntax
  4. Examples
    • Adding All Elements from Another Collection
    • Inserting All Elements at a Specific Position
    • Handling IndexOutOfBoundsException
  5. Real-World Use Case
  6. Conclusion

Introduction

The ArrayList class in Java is part of the java.util package and provides a resizable array implementation. The addAll() method is used to add multiple elements to the list, either appending them to the end or inserting them at a specified position.

addAll(Collection<? extends E> c) Method Syntax

The syntax for the addAll(Collection<? extends E> c) method is as follows:

public boolean addAll(Collection<? extends E> c)
  • c: The collection containing elements to be added to the list.

The method returns true if the ArrayList is modified as a result of this operation.

addAll(int index, Collection<? extends E> c) Method Syntax

The syntax for the addAll(int index, Collection<? extends E> c) method is as follows:

public boolean addAll(int index, Collection<? extends E> c)
  • index: The index at which to insert the first element from the specified collection.
  • c: The collection containing elements to be added to the list.

The method returns true if the ArrayList is modified as a result of this operation.

Examples

Adding All Elements from Another Collection

The addAll(Collection<? extends E> c) method appends all elements from the specified collection to the end of the ArrayList.

Example

import java.util.ArrayList;
import java.util.Arrays;

public class AddAllExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");

        ArrayList<String> moreFruits = new ArrayList<>(Arrays.asList("Orange", "Grapes"));

        list.addAll(moreFruits);

        System.out.println("ArrayList after addAll: " + list);
    }
}

Output:

ArrayList after addAll: [Apple, Banana, Orange, Grapes]

Inserting All Elements at a Specific Position

The addAll(int index, Collection<? extends E> c) method inserts all elements from the specified collection at the specified position in the ArrayList.

Example

import java.util.ArrayList;
import java.util.Arrays;

public class AddAllAtIndexExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");

        ArrayList<String> moreFruits = new ArrayList<>(Arrays.asList("Orange", "Grapes"));

        list.addAll(1, moreFruits);

        System.out.println("ArrayList after addAll at index 1: " + list);
    }
}

Output:

ArrayList after addAll at index 1: [Apple, Orange, Grapes, Banana]

Handling IndexOutOfBoundsException

If the specified index is out of range, the addAll(int index, Collection<? extends E> c) method throws an IndexOutOfBoundsException.

Example

import java.util.ArrayList;
import java.util.Arrays;

public class AddAllWithExceptionHandling {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");

        ArrayList<String> moreFruits = new ArrayList<>(Arrays.asList("Orange", "Grapes"));

        try {
            list.addAll(5, moreFruits); // This will throw an exception
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: Index: 5, Size: 2

Real-World Use Case

Merging Two Lists of Products

In an e-commerce application, you may have two lists of products: one for the current season and one for the upcoming season. You can use the addAll() method to merge these two lists for display on the website.

Example

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

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return name + " ($" + price + ")";
    }
}

public class ProductManager {
    public static void main(String[] args) {
        List<Product> currentSeason = new ArrayList<>(Arrays.asList(
            new Product("T-shirt", 19.99),
            new Product("Jeans", 49.99)
        ));

        List<Product> upcomingSeason = new ArrayList<>(Arrays.asList(
            new Product("Sweater", 29.99),
            new Product("Jacket", 79.99)
        ));

        // Merge the upcoming season products into the current season list
        currentSeason.addAll(upcomingSeason);

        // Display all products
        System.out.println("All Products:");
        currentSeason.forEach(product -> System.out.println(product));
    }
}

Output:

All Products:
T-shirt ($19.99)
Jeans ($49.99)
Sweater ($29.99)
Jacket ($79.99)

Conclusion

The ArrayList.addAll() method in Java provides a convenient way to add multiple elements to an ArrayList either at the end or at a specific position. By understanding how to use this method, you can efficiently manage and manipulate collections of data in your Java applications. Whether you are merging lists or inserting elements at a specific position, the addAll() method offers a flexible and powerful solution.

Comments