Java LinkedList clone() Method

Java LinkedList Java LinkedList


clone()The method is in JavaObjecta method of the class, used to create and return a copy of the current object. InLinkedListthe class, this method is overridden to implement a shallow copy of the linked list.

Key Points:

  • It returns a newLinkedListobject
  • The new linked list contains the same elements as the original linked list
  • The elements themselves are not copied (shallow copy)

Method Syntax

public Object clone()

Return Value:

  • Returns thisLinkedLista shallow copy of

Exceptions:

  • Does not throw any exception

How to Use the clone() Method

Basic Usage Example

Example

import java.util.LinkedList;

public class LinkedListCloneExample {
    public static void main(String[] args) {
        // Create the original linked list
        LinkedList<String> originalList = new LinkedList<>();
        originalList.add("Apple");
        originalList.add("Banana");
        originalList.add("Cherry");
       
        // Clone the linked list
        LinkedList<String> clonedList = (LinkedList<String>) originalList.clone();
       
        // Print both linked lists
        System.out.println("Original List: " + originalList);
        System.out.println("Cloned List: " + clonedList);
    }
}

Output:

Original List: [Apple, Banana, Cherry]
Cloned List: [Apple, Banana, Cherry]

Shallow Copy vs Deep Copy

Characteristics of Shallow Copy

  1. Element references are the same: The elements in the cloned linked list and the original linked list are the same objects
  2. Modifying an element affects both: If you modify an object in the linked list, both linked lists will be affected

Example

import java.util.LinkedList;

class Fruit {
    String name;
   
    Fruit(String name) {
        this.name = name;
    }
   
    @Override
    public String toString() {
        return name;
    }
}

public class ShallowCopyExample {
    public static void main(String[] args) {
        LinkedList<Fruit> original = new LinkedList<>();
        original.add(new Fruit("Apple"));
       
        LinkedList<Fruit> cloned = (LinkedList<Fruit>) original.clone();
       
        // Modify an element in the original linked list
        original.get(0).name = "Orange";
       
        System.out.println("Original: " + original);
        System.out.println("Cloned: " + cloned);
    }
}

Output:

Original: [Orange]
Cloned: [Orange]

How to Implement Deep Copy

If you need a completely independent copy (including elements), you need to manually implement deep copy:

Example

import java.util.LinkedList;

class Fruit implements Cloneable {
    String name;
   
    Fruit(String name) {
        this.name = name;
    }
   
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
   
    @Override
    public String toString() {
        return name;
    }
}

public class DeepCopyExample {
    public static void main(String[] args) throws CloneNotSupportedException {
        LinkedList<Fruit> original = new LinkedList<>();
        original.add(new Fruit("Apple"));
       
        LinkedList<Fruit> deepCloned = new LinkedList<>();
        for (Fruit fruit : original) {
            deepCloned.add((Fruit) fruit.clone());
        }
       
        // Modify an element in the original linked list
        original.get(0).name = "Orange";
       
        System.out.println("Original: " + original);
        System.out.println("Deep Cloned: " + deepCloned);
    }
}

Output:

Original: [Orange]
Deep Cloned: [Apple]

Practical Application Scenarios

  1. Protect original data: When you need to operate on a linked list but do not want to modify the original data
  2. Quick copy: When you need to quickly create a linked list with the same content
  3. Multithreaded environment: When using independent copies of the same data in different threads

Notes

  1. Type casting: clone() returns the Object type, and needs to be cast to LinkedList
  2. Element immutability: For immutable objects (such as String), shallow copy is sufficient
  3. Performance considerations: Cloning a large linked list incurs some performance overhead
  4. Concurrency issues: If the linked list is modified during cloning, it may lead to inconsistency

Frequently Asked Questions

Q1: What is the difference between the clone() method and direct assignment?

Direct assignment(such aslist2 = list1) just creates a new reference pointing to the same object, whileclone()creates a new independent object.

Q2: Why does the clone() method return Object instead of LinkedList?

This is in Javaclone()the standard design of the method, requiring subclasses to override it and return a more specific type.

Q3: How to clone a LinkedList of custom objects?

Make sure the custom class implementsCloneablethe interface and overrides theclone()method, then follow the approach in the deep copy example.


Summary

LinkedListofclone()The method provides a way to quickly create a copy of a linked list, but note that it is a shallow copy. Choose to use shallow copy or implement deep copy according to actual needs, especially when dealing with linked lists containing mutable objects.

Java LinkedList Java LinkedList

Other Extensions