Java ArrayList.addAll(): Merging & Splicing Collections

The ArrayList.addAll() method appends or inserts all elements from a specified Collection into an ArrayList in a single bulk memory copy (System.arraycopy()), returning true if the target list changed.

Related List Operations: For adding a single item, see ArrayList.add(). For bulk removal or intersection of collections, explore ArrayList.removeAll() and ArrayList.retainAll(). To pre-allocate capacity before merging multiple lists, use ArrayList.ensureCapacity().

1. Syntax & Overloaded Method Signatures 🔝

Declared in java.util.ArrayList<E>:

 // 1. Append all elements of collection c to the end of this list
public boolean addAll(Collection<? extends E> c)

 // 2. Insert all elements of collection c starting at the specified 0-based index
public boolean addAll(int index, Collection<? extends E> c)
Overload Signature Return Type Time Complexity Operational Rule
addAll(Collection<? extends E> c) boolean O(k) Appends all k elements of c at the end in iterator order; returns true if k > 0.
addAll(int index, Collection<? extends E> c) boolean O(n + k) Inserts all k elements at index, shifting existing tail elements right by k slots.

2. Appending a Second ArrayList at the End 🔝

Calling languages.addAll(languages2) copies every element from languages2 to the end of languages and returns true (which can be verified inside an if-else statement):

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");

ArrayList<String> languages2 = new ArrayList<String>();
languages2.add("HTML");
languages2.add("JavaScript");
languages2.add("CSS");

if (languages.addAll(languages2)) {
    System.out.println("Added all elements at end");
}
System.out.println(languages);

Terminal Output:

Added all elements at end
[Java, PHP, Python, HTML, JavaScript, CSS]

3. Splicing a Collection at a Specific Index 🔝

Using the 2-argument overload languages.addAll(2, languages2) inserts all elements of languages2 starting at index 2 (right after "PHP"), shifting "Python" to the end:

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "Python"));
ArrayList<String> languages2 = new ArrayList<>(Arrays.asList("HTML", "JavaScript", "CSS"));

languages.addAll(2, languages2);  // Insert at index 2 (before "Python")
System.out.println(languages);

Terminal Output:

[Java, PHP, HTML, JavaScript, CSS, Python]

4. When addAll() Returns false & Exception Rules 🔝

addAll() returns false if and only if the passed collection is empty (because the target list was not modified). Passing a null collection reference throws a NullPointerException, and passing an invalid index (index < 0 || index > size()) throws an IndexOutOfBoundsException:

ArrayList<String> target = new ArrayList<>();
target.add("Core");

ArrayList<String> emptyList = new ArrayList<>();
System.out.println("Empty addAll returns: " + target.addAll(emptyList));  // false

try {
    target.addAll(null);  // Passing null throws NullPointerException!
} catch (NullPointerException ex) {
    System.out.println("Caught null collection: NullPointerException");
}

Terminal Output:

Empty addAll returns: false
Caught null collection: NullPointerException

5. Upper-Bounded Wildcard Covariance (Collection<? extends E>) 🔝

Because the parameter type is Collection<? extends E>, you can pass any Set, List, or Queue whose element type is E or a subclass of E (for example, adding List<Integer> and List<Double> into an ArrayList<Number>):

ArrayList<Number> numbers = new ArrayList<>();
numbers.add(100);

 // Collection accepts List and List
numbers.addAll(Arrays.asList(10, 20));
numbers.addAll(Arrays.asList(3.5, 7.25));
System.out.println("Numbers: " + numbers);

Terminal Output:

Numbers: [100, 10, 20, 3.5, 7.25]

6. Comparison: addAll() vs Loop of add() vs Collections.addAll() 🔝

Why bulk insertion outperforms manual element-by-element loops:

Approach Resizing / Shifting Performance & Best Use Case
list.addAll(otherList) Single capacity check + 1 arraycopy Fastest way to append an existing Collection.
list.addAll(idx, otherList) Shifts tail once by k slots O(n + k) vs O(n * k) for a loop of add(idx, e).
Collections.addAll(list, a, b, c) Appends varargs array directly Best when adding inline literal elements without creating a temporary list.

7. Production Recipe: Merging Two ArrayLists Without Duplicates 🔝

Because ArrayList.addAll() keeps duplicates by default, combine it with LinkedHashSet when you need an order-preserving union of two lists:

public class MergeDeduplicate {
    public static void main(String[] args) {
        LinkedHashSet<String> unique = new LinkedHashSet<>(Arrays.asList("Ana", "Ben", "Cid"));
        unique.addAll(Arrays.asList("Ben", "Dan", "Ana"));
        ArrayList<String> merged = new ArrayList<>(unique);
        System.out.println("Merged Unique: " + merged);
    }
}

Terminal Output:

Merged Unique: [Ana, Ben, Cid, Dan]

8. Practical Recipe: Aggregating Paginated API Batches 🔝

Pre-sizing the destination ArrayList using combined size() counts before calling addAll() guarantees zero intermediate array reallocations:

public class BatchAggregator {
    public static void main(String[] args) {
        ArrayList<String> allOrders = new ArrayList<>(4);
        allOrders.addAll(Arrays.asList("ORD-101", "ORD-102"));
        allOrders.addAll(Arrays.asList("ORD-103", "ORD-104"));
        System.out.println("Total Orders (" + allOrders.size() + "): " + allOrders);
    }
}

Terminal Output:

Total Orders (4): [ORD-101, ORD-102, ORD-103, ORD-104]

9. Common Developer Pitfalls & Traps 🔝

Shallow Copy of Object References

Like ArrayList.clone(), addAll() copies object references, not deep clones of mutable objects. Mutating a mutable object inside list2 after list1.addAll(list2) will affect the object seen in list1.

Passing a Potentially Null Collection Without a Guard

Unlike an empty list, passing null to list.addAll(null) immediately throws a NullPointerException (because addAll calls c.toArray() internally). Use if (c != null) list.addAll(c); when merging external inputs.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListAddAllFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "D"));
        if (list.addAll(1, Arrays.asList("B", "C")) && list.size() == 4) {
            System.out.println("Check 1 Passed: Spliced [B, C] at index 1 -> " + list);
        }
        if (!list.addAll(new ArrayList<>())) {
            System.out.println("Check 2 Passed: Empty collection returned false.");
        }
        System.out.println("All ArrayList.addAll() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: Spliced [B, C] at index 1 -> [A, B, C, D]
Check 2 Passed: Empty collection returned false.
All ArrayList.addAll() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Does list1.addAll(list2) modify list2?

No. The source collection list2 remains completely unchanged; its elements are copied into list1.

What happens if I call list.addAll(list) on itself?

Because ArrayList.addAll() first snapshots the argument via c.toArray() before mutating the backing array, list.addAll(list) safely duplicates all current elements once without entering an infinite loop.

Why is addAll(index, c) faster than calling add(index, e) in a loop?

addAll(index, c) shifts the existing tail elements only once by c.size() positions, whereas calling add(index, e) in a loop shifts the tail on every single iteration.

Can I pass a HashSet or LinkedList to ArrayList.addAll()?

Yes. Any class implementing java.util.Collection (including HashSet, TreeSet, LinkedList, and ArrayDeque) can be passed directly to addAll().

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer