Java ArrayList.addAll() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about addAll() method of java.util.ArrayList class. It is used to add all the elements from one list to the another list.

syntax

Appends all of the elements in the specified collection to the end of this list.

 boolean java.util.ArrayList.addAll(Collection<? extends E> c)

Param

c collection containing elements to be added to this list.

Return

true if this list changed as a result of the call.

Exception

NullPointerException if the specified collection is null

Java ArrayList addAll() example

Refer below steps

  • Constructs three ArrayList namely fruits, vegetables, and fruitsAndVegetables.
  • Add some elements in fruits and vegetables ArrayList using add() method.
  • We have added all the elements from "fruits" and "vegetables" List to "fruitsAndVegetables" ArrayList.
  • Verify size of each ArrayList and print the content of fruitsAndVegetables ArrayList.
package com.technicalkeeda.app;

import java.util.ArrayList;

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

        ArrayList <String> fruits = new ArrayList <String> ();
        fruits.add("Apples");
        fruits.add("Pears");
        fruits.add("Bananas ");

        ArrayList <String> vegetables = new ArrayList <String> ();
        vegetables.add("Cauliflower");
        vegetables.add("Cabbage");
        vegetables.add("Drumstick");

        ArrayList <String> fruitsAndVegetables = new ArrayList <String> ();
        fruitsAndVegetables.addAll(fruits);
        fruitsAndVegetables.addAll(vegetables);

        System.out.println("fruits list size:- " + fruits.size());
        System.out.println("vegetables list size:- " + vegetables.size());
        System.out.println("fruitsAndVegetables list size after addAll():- " + fruitsAndVegetables.size());

        System.out.println("\nPrint fruitsAndVegetables list");
        for (String str: fruitsAndVegetables) {
            System.out.println(str);
        }
  
    }
}

Output

fruits list size:- 3
vegetables list size:- 3
fruitsAndVegetables list size after addAll():- 6

Print fruitsAndVegetables list
Apples
Pears
Bananas 
Cauliflower
Cabbage
Drumstick


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0314 seconds.