Jas
Jas

Reputation: 79

How to create a deep copy of a linked list if objects stored in the list are not cloneable?

I have a linkedlist which contains objects that are not cloneable. What would be the most efficient way to deep copy the list?

What I have tried is:

List<Ob> deepCopyListA = new LinkedList<Ob>(aList);

and it seems to work fine, but I am just wondering if it is actually deep copying the whole list and if there is any better way to do it

*I am not sure what codes to post, but basically I have a class, and a number of instances of the class as a list in another class

private List<Ob> aList;

public List<Ob> getaList() {
    List<Ob> deepCopyListA = new LinkedList<Ob>(aList);
    return deepCopyListA;
}

Upvotes: 0

Views: 3130

Answers (1)

alexroussos
alexroussos

Reputation: 2681

You could go with the straight-forward but brittle approach of manually copying each property from the old objects into the new objects. Or you could clone the objects using reflection (there are libraries that will do this for you).

You can read more about some of the various approaches and tradeoffs in this post: Java: recommended solution for deep cloning/copying an instance

Upvotes: 0

Related Questions