Open In App

How to Copy and Add all List Elements to an Empty ArrayList in Java?

Last Updated : 04 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

We can copy and add List items in Array List using addAll() method. This method accepts a Collection (Ex. List) as an argument and adds the collection items at the end of its calling Collection (Ex. ArrayList). This method returns a boolean value. addAll() return true if the collection successfully adds else it returns false.

We can clone the list by two ways:

  1. Using addAll() method
  2. Using a copy constructor

Method 1: Using addAll() method

Syntax:

public boolean addAll(Collection c);

Parameter: It accepts a collection to be cloned as its parameter

Return Value: This method returns a boolean value. addAll() return true if the collection successfully adds else it returns false.

Exception: It will throw Null Pointer Exception if the specified Collection is null.

Java




// Java program to clone the list
  
import java.util.ArrayList;
import java.util.List;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create ArrayList
        ArrayList<String> ArrList = new ArrayList<String>();
  
        // Adding elements to the ArrayList
        ArrList.add("item 1");
        ArrList.add("item 2");
        ArrList.add("item 3");
  
        System.out.println("ArrayList = " + ArrList);
  
        // create List
        List<String> ListItem = new ArrayList<String>();
        ListItem.add("item 4");
        ListItem.add("item 5");
  
        // add List items in ArrayList
        ArrList.addAll(ListItem);
  
        System.out.println(
            "After Adding List Item in ArrayList = "+ ArrList);
    }
}


Output

ArrayList = [item 1, item 2, item 3]
After Adding List Item in ArrayList = [item 1, item 2, item 3, item 4, item 5]

Method 2: Using a copy constructor

Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection.

Syntax:

ArrayList arrlist = new ArrayList(collection c);

Here, c is the collection containing elements to be added to this list.

Approach:

  1. Create a list to be cloned.
  2. Clone the list bypassing the original list as the parameter of the copy constructor of ArrayList.

Java




// Program to clone a List in Java 
    
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
    
class Example { 
    public static void main(String[] args) 
    
        // Create a list 
        List<String> original = Arrays.asList( 
                "GeeksForGeeks"
                "Coding"
                "Portal"); 
    
        // Clone the list 
        List<String> cloned_arraylist 
            = new ArrayList<String>(original); 
    
        System.out.println(cloned_arraylist); 
    
}


Output

[GeeksForGeeks, Coding, Portal]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads