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 both overloaded versions of this method, explain how they work, and provide examples to demonstrate their functionality. Additionally, we will cover a real-world use case to illustrate its application.

Table of Contents

  1. Introduction
  2. addAll Method Syntax
    • addAll(Collection<? extends E> c)
    • addAll(int index, Collection<? extends E> c)
  3. How They Work
  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 a powerful operation that allows you to add multiple elements from another collection to the ArrayList. This method comes in two forms: one that appends all elements to the end of the list, and another that inserts all elements at a specified position.

addAll Method Syntax

addAll(Collection<? extends E> c)

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)

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.

How They Work

addAll(Collection<? extends E> c)

When you use addAll(Collection<? extends E> c), the method appends all elements from the specified collection to the end of the ArrayList. Internally, it iterates over the elements of the specified collection and adds them to the ArrayList, expanding its capacity if necessary.

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

When you use addAll(int index, Collection<? extends E> c), the method inserts all elements from the specified collection at the specified position in the ArrayList. Internally, it checks if the index is within the bounds of the list, then shifts the existing elements to the right to make space for the new elements, and finally adds the elements from the specified collection.

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;
import java.util.List;

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

        List<String> moreFruits = 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;
import java.util.List;

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

        List<String> moreFruits = 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;
import java.util.List;

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

        List<String> moreFruits = 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top