Home » Java programming language

Java Collections addAll() Method with Example

Collections Class addAll() method: Here, we are going to learn about the addAll() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on January 07, 2020

Collections Class addAll() method

  • addAll() Method is available in java.lang package.
  • addAll() Method is used to put all the given elements(ele) to the given collection (co).
  • addAll() Method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • addAll() Method may throw an exception at the time of add the elements(ele) to the given Collection(co).
    • UnsupportedOperationException: This exception may throw when collection unsupport add() method.
    • NullPointerException: This exception may throw when elements (ele) may have at least one null & the given collection unsupport null.
    • IllegalArgumentException: This exception may throw when the given element (ele) is not valid.

Syntax:

    public static boolean addAll(Collection co, Type.. ele);

Parameter(s):

  • Collection co – represents the container of "Collection" type.
  • Type.. ele – represents the elements to add into given collection co.

Return value:

The return type of the method is Boolean, it returns true when the given set of elements(ele) to be added into collection successfully otherwise it returns false.

Example:

// Java Program is to demonstrate the example
// of boolean addAll(Collection co, Type.. ele) of Collections class

import java.util.*;

public class AddAll {
    public static void main(String args[]) {
        // Create a linked list object     
        List link_list = new LinkedList();

        // By using add() method is to add the
        // given elements in linked list
        link_list.add(10);
        link_list.add(20);
        link_list.add(30);
        link_list.add(40);
        link_list.add(50);

        //Display Linked List
        System.out.println("link_list: " + link_list);

        // By using addAll() method is to add all the
        // elements in the given collection linked list
        boolean status = Collections.addAll(link_list, 60, 70, 80, 90);

        System.out.println();
        System.out.println("Collections.addAll(link_list, 60,70,80,90) :");

        // Display Linked List
        System.out.println("link_list: " + link_list);
    }
}

Output

link_list: [10, 20, 30, 40, 50]

Collections.addAll(link_list, 60,70,80,90) :
link_list: [10, 20, 30, 40, 50, 60, 70, 80, 90]



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.