LinkedList clone() Method in Java
Last Updated :
16 Dec, 2024
Improve
In Java, the clone() method of LinkedList, creates a shallow copy which means the structure is duplicated but the objects inside the list are shared between the original and the copied list. So, the cloned list will have the same elements as the original list.
Syntax of Java LinkedList clone() Method
public Object clone()
- Return type: This method returns a copy of the instance of LinkedList.
Example: Here, we use the clone() method to return the copy of the given LinkedList as an Object.
// Java program to Demonstrate the
// working of clone() in LinkedList
import java.util.LinkedList;
public class Geeks {
public static void main(String args[]) {
LinkedList<String> l = new LinkedList<>();
// Use add() method to add
// elements in the LinkedList
l.add("Geeks");
l.add("for");
l.add("Geeks");
System.out.println("Original LinkedList: " + l);
// create another list
// and copy the elements
LinkedList l2 = new LinkedList();
l2 = (LinkedList)l.clone();
System.out.println("Clone LinkedList is: " + l2);
}
}
Output
Original LinkedList: [Geeks, for, Geeks] Clone LinkedList is: [Geeks, for, Geeks]