Collections

how to copy a LinkedList to another LinkedList using the collections
Previous Home Next

 

In this example we shall see how can we copy LinkedList to another LinkedList.

In this example we have created a class CollectionExample. For using LinkedList we have
to import the java.util package.
 In this example we have used the copy() method defined in the java.util.Collections package. The copy() method have the following syntax:
 
void copy(List destlist, List sourcelist);

where destlist is the list to which the sourcelist is to be copied.


In this example we have created two linked lists namely list and stringlist then we add some elements to both of lists and added all the contents of the stringlist to the list by using the addAll() method. The we have invoked the copy() method on the Collections class. The following statement in the given example does exactly the same,

Collections.copy(list, stringlist);   
here list is the destlist to which the sourcelist i.e stringlist is to be copied.

 
package r4r.co.in;
import java.util.*;
import java.util.ListIterator;


public class CollectionExample {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub


LinkedList<Object> list=new LinkedList<Object>(); // creating a LinkedList of Object type elements
list.add(1); // adding integer values to the LinkedList
list.add(2);
list.add("r4r"); // adding String values to the LinkedList
list.add("shashi");
list.add("s/w engineer");
System.out.println("The contents of the object list are :");
ListIterator<Object> ltr=list.listIterator();
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}

LinkedList<String> stringlist=new LinkedList<String>();
stringlist.add("This");
stringlist.add("is");
stringlist.add("good");
stringlist.add("example");
System.out.println("The elements of the created string list are: ");
System.out.println(stringlist);
list.addAll(stringlist);
ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
System.out.println("The contents of the added list are as follows :");
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}


Collections.copy(list, stringlist); // here we are copying the stringlist(source list) to the list(destination list) by using copy method
ltr=list.listIterator();
System.out.println("After copying the list the resulting list is as follows : ");
while(ltr.hasNext())
{
System.out.println(ltr.next());
}


}


}
The output of the above written program will be as follows:

The contents of the object list are :
1
2
r4r
shashi
s/w engineer
The elements of the created string list are:
[This, is, good, example]
The contents of the added list are as follows :
1
2
r4r
shashi
s/w engineer
This
is
good
example
After copying the list the resulting list is as follows :
This
is
good
example
s/w engineer
This
is
good
example

Previous Home Next