Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java LinkedList clone: copied nodes, shared element objects

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

LinkedList.clone creates a new list structure while retaining references to the original element objects.

This complete Java 8 program has a checked output. Compile it as the named public class, then run it without additional libraries.

Membership and element ownership differ

Removing a record from the copy does not remove a node from the original. Changing a mutable record already present in both lists is visible from both. This is a shallow copy, and an ordinary copy constructor has the same element-sharing issue.

The fixture uses a named InvoiceFlag object so the shared reference is observable. The two collections are distinct, but their first element has the same identity. An immutable element model or deliberate element-copy operation is needed when consumers must not share state.

Do not call this a snapshot of a mutable graph

Copying n node references costs linear time and additional node storage. It does not copy every object reachable through those references. A process boundary needs serialization rules and schema handling; clone supplies neither. Views and snapshots examines the related membership question.

Working program

Java
import java.util.LinkedList;
public class InvoiceFlagCopy {
    static final class InvoiceFlag {
        String state;
        InvoiceFlag(String state) { this.state = state; }
    }
    public static void main(String[] args) {
        LinkedList<InvoiceFlag> original = new LinkedList<>();
        original.add(new InvoiceFlag("queued"));
        LinkedList<InvoiceFlag> copy = (LinkedList<InvoiceFlag>) original.clone();
        copy.getFirst().state = "reviewed";
        System.out.println("shared=" + (original.getFirst() == copy.getFirst()));
        System.out.println("original=" + original.getFirst().state);
        copy.clear();
        System.out.println("sizes=" + original.size() + "," + copy.size());
    }
}

Output

Output
shared=true
original=reviewed
sizes=1,0

Costs and boundaries

Cloning a list with n elements costs O(n) time and O(n) new node space. The memory of each referenced element is still shared until the application copies it separately.

Common Mistakes

  • Do not infer deep copy from distinct list identities.
  • Do not expose mutable elements as though an unmodifiable wrapper froze them.
  • Do not use clone as a serialization or tenant-isolation boundary.

Read next

Java LinkedList: operations, internals and failure cases, Java collection views: live wrappers, snapshots and shallow copies, Java collection factories: rejected updates and shallow element ownership.

java
linkedlist-shallow-copy
Storage details