1. Introduction
The LinkedList class in Java comes with a method named clone(), which is used to create a shallow copy of the list. A shallow copy means the elements themselves are not cloned, but the structure of the list is copied. In this blog post, we’ll demonstrate how to use the clone() method to create a copy of a LinkedList.
2. Program Steps
1. Create and initialize a LinkedList.
2. Print the original LinkedList.
3. Use the clone() method to create a copy of the LinkedList.
4. Print the cloned LinkedList.
3. Code Program
import java.util.LinkedList;
public class LinkedListCloneExample {
public static void main(String[] args) {
// Step 1: Create and initialize a LinkedList
LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Print the original LinkedList
System.out.println("Original LinkedList: " + fruits);
// Step 3: Use the clone() method to create a copy of the LinkedList
LinkedList<String> clonedFruits = (LinkedList<String>) fruits.clone();
// Step 4: Print the cloned LinkedList
System.out.println("Cloned LinkedList: " + clonedFruits);
}
}
Output:
Original LinkedList: [Apple, Banana, Cherry] Cloned LinkedList: [Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: A LinkedList named fruits is created and initialized with the elements "Apple", "Banana", and "Cherry".
Step 2: The original LinkedList is printed to the console, showing the elements it contains.
Step 3: The clone() method is called on the fruits LinkedList, creating a shallow copy named clonedFruits. The elements themselves are not cloned, but the structure of the list is copied.
Step 4: The cloned LinkedList, clonedFruits, is printed to the console, and it contains the same elements as the original list, confirming that the clone() method has worked successfully.
By following these steps, you can efficiently create a shallow copy of a LinkedList in Java using the clone() method.