Collections

how to create a clone of LinkedList in collections
Previous Home Next

 

In this example we shall see how can we create the clone of a Linked List.

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 clone() method on the object of the LinkedList for creating the clone of it. The syntax of the clone() method is:

Object clone()     
This method returns a copy of the LinkedList object.

In this example we have created a LinkedList list and then added some elements to it. Also we have created another LinkedList name listclone which stores the elements which are returned while invoking the clone() on the list. The following statement of the given example creates the clone of  the list. Finally we have displayed the elements of the cloned list i.e. listclone.
LinkedList<Object> listclone=(LinkedList<Object>)list.clone();


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


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 peek method retruns :"+list.peek()); // this retrieves the first element i.e. head of linked list
//System.out.println("The poll method returns :"+list.poll()); // this retrieves and removes the first element i.e. head of the LinkedList
LinkedList<Object> listclone=(LinkedList<Object>)list.clone(); //creating a clone of LinkedList list
System.out.println("The content of the cloned list is :"+listclone); // displaying the contents of the cloned list
listclone.remove(2); //removing the element at index 2 from the listclone
System.out.println("Now the contents of the list are :"+listclone); // displaying the contents of the listclone after removing the element
System.out.println("The contents of the original list are as follows: ");

ListIterator<Object> ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}


}


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

The content of the cloned list is :[1, 2, r4r, shashi, s/w engineer]
Now the contents of the list are :[1, 2, shashi, s/w engineer]
The contents of the original list are as follows:
1
2
r4r
shashi
s/w engineer

Previous Home Next