Thursday 26 July 2012

Copying data from one LinkedList to another LinkedList in Java

Many a times you need to create a copy of LinkedList for this purpose you can use addAll(Collection c) method of LinkedList in Java to copy all elements from on LinkedList to another LinkedList in Java.

The complete source code is given below:


import java.util.LinkedList;

public class CopyFromOneLinkedListToAnotherLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Add elements to Arraylist

  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("Original Linkedlist contains : ");

  for (Object e : lList) {

   System.out.println(e);
  }

  // create an LinkedList object for copying.

  LinkedList lListCopy = new LinkedList();

  /**
   * 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.
   **/

  lListCopy.addAll(lList);

  System.out.println("Copied Linkedlist contains : ");

  for (Object e : lListCopy) {

   System.out.println(e);
  }

 }

}


The output is:




Original Linkedlist contains :
1
2
3
Copied Linkedlist contains :
1
2
3

No comments:

Post a Comment