How to Copy and Add all List Elements to an Empty ArrayList in Java?
Last Updated :
04 Dec, 2020
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:
- Using addAll() method
- 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
import java.util.ArrayList;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> ArrList = new ArrayList<String>();
ArrList.add( "item 1" );
ArrList.add( "item 2" );
ArrList.add( "item 3" );
System.out.println( "ArrayList = " + ArrList);
List<String> ListItem = new ArrayList<String>();
ListItem.add( "item 4" );
ListItem.add( "item 5" );
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:
- Create a list to be cloned.
- Clone the list bypassing the original list as the parameter of the copy constructor of ArrayList.
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Example {
public static void main(String[] args)
{
List<String> original = Arrays.asList(
"GeeksForGeeks" ,
"Coding" ,
"Portal" );
List<String> cloned_arraylist
= new ArrayList<String>(original);
System.out.println(cloned_arraylist);
}
}
|
Output
[GeeksForGeeks, Coding, Portal]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...