Reputation: 9
i have a linkedlist and i want to make a copy of that linkedlist. does clone run faster than create new instance and then assign value for it ? for example i have
LinkedList<MyClass> list = new LinkedList<MyClass>();
list.add(instance1);
list.add(instance2);
Use clone:
LinkedList<MyClass> list2 = list.clone();
Use constructor:
LinkedList<MyClass> list2 = new LinkedList<MyClass>();
for(MyClass myclass : list){
list2.add(myclass);
}
Upvotes: 1
Views: 44
Reputation: 121998
Best is use the shallow copy constructor. You wrote Use constructor and not using. You are looping on it.
Among all I would suggest to use
List<MyClass> list2 = new LinkedList<MyClass>(list);
Even Josh Bloch suggest the same
The truth of the matter is that you don't provide any capability to your clients by implementing Cloneable and providing a public clone method other than the ability to copy. This is no better than what you get if you provide a copy operation with a different name and you don't implement Cloneable. That's basically what you're doing with a copy constructor. The copy constructor approach has several advantages, which I discuss in the book. One big advantage is that the copy can be made to have a different representation from the original. For example, you can copy a LinkedList into an ArrayList.
Upvotes: 2