Description
Program to add all the elements of a List to the LinkedList using addAll() method of LinkedList class.
Example
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; class LinkedListAddAll { public static void main(String[] args) { // create a LinkedList LinkedList<String> list = new LinkedList<String>(); // Add elements to the LinkedList list.add("AA"); list.add("BB"); list.add("CC"); list.add("DD"); // Displaying linked list before add System.out.println("Before: LinkedList: " + list); // create a new list having few elements List<String> arrayList = new ArrayList<String>(); arrayList.add("Item1"); arrayList.add("Item2"); arrayList.add("Item3"); // Append the list elements to LinkedList list.addAll(arrayList); // Displaying the LinkedList after addAll System.out.println("After: LinkedList: " + list); } }
Output:
Before: LinkedList: [AA, BB, CC, DD] After: LinkedList: [AA, BB, CC, DD, Item1, Item2, Item3]
addAll() method:
public boolean addAll(Collection<? extends E> c)
: Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator. Source: addAll() method – Javadoc.
Leave a Reply