Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

addAll()

Example

Merge items from one list into another

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList<String> cars = new LinkedList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda"); LinkedList<String>

brands = new LinkedList<String>();

brands.add("Microsoft");

brands.add("Code7Schools");

brands.add("Apple");

brands.addAll(cars);

System.out.println(brands); } }

Definition and Usage

The addAll() method inserts all items from a collection into the list.

When an index is specified, the new items will be positioned at that index, displacing all subsequent elements in the list.

If no index is provided, the new items will be added to the end of the list.

Syntax

public boolean addAll(Collection<T> items)
public boolean addAll(int index, Collection<T> items)

T represents the data type of elements in the list.

Parameter Values

Parameter

Description

index

Optional. Indicates the position in the list where the items should be added.

items

Mandatory. Refers to a collection containing items to be appended to the list.

Technical Details

Returns:

It returns true if the list is altered and false otherwise.

Throws:

IndexOutOfBoundsException occurs if the index is negative or exceeds the size of the list.

NullPointerException is thrown if the collection is null.

More Examples

Example

Insert items at a specified position within the list.

import java.util.LinkedList;

public class Main { public static void main(String[] args) {

LinkedList<String> cars = new LinkedList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda"); LinkedList<String>

brands = new LinkedList<String>();

brands.add("Microsoft");

brands.add("Code7school");

brands.add("Apple");

brands.addAll(1, cars);

System.out.println(brands); } }