Press "Enter" to skip to content

List addAll() Method in Java

addAll(Collection c) method of List appends all the elements of the specified collection to the end of the List instance. The specified collection’s iterator defines the order of added elements. The behavior of this method is undefined if someone modifies the supplied collection during this operation.

Syntax:

Let’s look at the syntax of List addAll()

boolean addAll(Collection<? extends E> c)
Freshers Placement

Parameters:
c – The specified collection that needs to be appended to the List.

Return:
If the operation is successful then the method returns true, else it returns false.

Exceptions:

NullPointerException – If the specified collection contains any null element and List implementation does not permit null values or the collection itself is null.
UnsupportedOperationException – Some List implementation doesn’t support the addAll() method, in that case, a call to this method results in an exception.

Example 1:

Let’s look at the addAll() example with ArrayList implementation.

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

// This program demonstrates
// the use of List addAll() method
// with ArrayList implementation
public class ListDemo {
	public static void main(String[] args) {

		// Instantiate the List with
		// ArrayList implementation
		List<Integer> list = new ArrayList<>();
		list.add(50);
		list.add(60);
		list.add(70);

		System.out.println(list);

		// Create collection
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(250);
		arrList.add(350);
		arrList.add(400);

		System.out.println(arrList);

		// this call will append
		// elements of arrList to the end of list
		list.addAll(arrList);

		System.out.println(list);
	}
}

Output:

[50, 60, 70]
[250, 350, 400]
[50, 60, 70, 250, 350, 400]

Example 2:

Freshers Placement

Let’s look at the addAll() example with LinkedList implementation.

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

// This program demonstrates
// the use of List addAll() method
// with LinkedList implementation
public class ListDemo {
	public static void main(String[] args) {

		// Instantiate the List with
		// LinkedList implementation
		List<Integer> list = new LinkedList<>();
		list.add(50);
		list.add(60);
		list.add(70);

		System.out.println(list);

		// Create collection
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(400);
		arrList.add(500);
		arrList.add(600);

		System.out.println(arrList);

		// this call will append
		// elements of arrList to the end of linked list
		list.addAll(arrList);

		System.out.println(list);
	}
}

Output:

[50, 60, 70]
[400, 500, 600]
[50, 60, 70, 400, 500, 600]

Related Articles:

Java.util.ArrayList.addAll() Method

Comments are closed.