Java LinkedList clone() Method Example

The clone() method of java.util.LinkedList class will create a shallow copy of the LinkedList.

1. Create a new LinkedList object(list1)
2. Add elements to the list1 using add() method
3. Create a new LinkedList list2
4. Use clone() method to copy the contents of list1 into list2

Signature

public Object clone()

This method creates a shallow copy of this LinkedList. The elements themselves are not cloned.

Example

The following example shows the usage of java.util.LinkedList.clone() method.

import java.util.LinkedList;

public class CloneMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList list1= new LinkedList();
		
		// use add() method to add elements to the LinkedList
		list1.add("Element1");
		list1.add("Element2");
		list1.add("Element3");

		//Printing the elements of the LinkedList list1
		System.out.println("Elements of the list1");
		for(String temp:list1)
		{
			System.out.println(temp);
		}
		
		// create another empty LinkedList
		LinkedList list2 = new LinkedList();
		//Shallow copying of list1 to list2
                list2 =(LinkedList)list1.clone();
		
		//Printing the elements of the LinkedList list2
		System.out.println("Elements of the list2");
		for(String temp:list2)
		{
			System.out.println(temp);
		}
	}
}

Output

Elements of the list1
Element1
Element2
Element3
Elements of the list2
Element1
Element2
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *