How to Copy and Add all List Elements to an Empty ArrayList in Java?
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
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.
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.
ArrayList arrlist = new ArrayList(collection c);
Here, c is the collection containing elements to be added to this list.
- Create a list to be cloned.
- Clone the list bypassing the original list as the parameter of the copy constructor of ArrayList.
[GeeksForGeeks, Coding, Portal]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.