LinkedList.clone creates a new list structure while retaining references to the original element objects.
Java LinkedList clone: copied nodes, shared 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
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
shared=true
original=reviewed
sizes=1,0Costs 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.
