java.util.List does not have a public clone method. I usually do something like:
List<Thing> copy = new ArrayList<Thing>(original);
//go through copy and do a deeper copy if needed:
for(ListInterator<Thing> i = copy.listIterator(); i.hasNext(); ) {
i.set(i.next().clone());
}
> Hi, I have a List. I want to clone it. How can I do
> this. I don't want to cast to the implementation
> level and call the clone method on that cos then I'm
> restricted to that implementation. How can I do this
>
> Thanks
something like
T[] temp = new T[oldList.size()];
temp = oldList.toArray(temp);
List<T> newList = Arrays.asList(temp);
> > T[] temp = new T[oldList.size()];
> > temp = oldList.toArray(temp);
> > List<T> newList = Arrays.asList(temp);
>
> I don't see the advantage of going through T[] -- the
> resulting list is a fixed-size list.
I think both Dr's reply and mine don't take into account that the OP wants
to rule out the new ArrayList(). Would he be sure that this is an ArrayList,
the casting method would do the trick.
On the other hand, the array method proposed here seems to avoid
the new ArrayList().
> On the other hand, the array method proposed here seems to avoid
> the new ArrayList().
Yes, but what it creates is a List backed by an array (the given array). Is
that any better that ArrayList, a list backed by an array? In fact it's worse,
since the first list is of fixed size!