Cloneing a list

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
[229 byte] By [megasteoa] at [2007-11-27 4:00:06]
# 1

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());

}

DrLaszloJamfa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...
# 2
Collections.copy()
baftosa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...
# 3
> Collections.copy(dst, src)Depends what you are trying to do. That method assumes dst exists and is big enough (two *major* assumptions). It also just copies references -- no deep copying.
DrLaszloJamfa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...
# 4

> 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);

CodeOnFire-againa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...
# 5
> 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.
DrLaszloJamfa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...
# 6

> > 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().

baftosa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...
# 7

> 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!

DrLaszloJamfa at 2007-7-12 9:04:42 > top of Java-index,Java Essentials,Java Programming...