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.ArrayList;
public class Main { 
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
        ArrayList<String> brands = new ArrayList<String>();
    brands.add("Microsoft");
    brands.add("W3Schools");
    brands.add("Apple");
    brands.addAll(cars);
    System.out.println(brands);
  }
}

Definition and Usage

The addAll() method appends all items from a collection to the list.

When an index is specified, the new items will be inserted at that position, shifting all subsequent elements in the list forward.

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

Syntax

Choose one of the following:

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

T denotes the data type of items in the list.

Parameter Values

Parameter

Description

index

Optional: The position in the list where the item should be added.

items

Required: The item that will be added to the list.

Technical Details

Returns:

It returns true if the list has been altered, and false otherwise.

Throws

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

More Examples

Example

Insert items at a specific position within the list.

import java.util.ArrayList;
public class Main { 
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
        ArrayList<String> brands = new ArrayList<String>();
    brands.add("Microsoft");
    brands.add("W3Schools");
    brands.add("Apple");
    brands.addAll(1,cars);
    System.out.println(brands);
  }
}