Click to See Complete Forum and Search --> : [1.0/1.1] Copying an ArrayList to another
JenniferBabe
Jun 3rd, 2006, 01:02 PM
Hi. I'm passing an arraylist to a method in which I want to copy it. I did it as:
ArrayList al....
add values to al....
call method: method(al)
...
another class:
ArrayList te;
.....
public void method(ArrayList al)
{ te = al;
}
Now it is assigning, but if I'm back in the original class and I change ArrayList al, the value of te is also changing. Does anyone knows how to fix this problem? I just want to copy the value of al to te in the method, not the actual pointer to the ArrayList.
JenniferBabe
Jun 3rd, 2006, 01:46 PM
This is working:
for(int x=0 ; x<al.Count ; x++)
{
this.te.Add(al[x].ToString());
}
But is there a shorter way of doing this?
ComputerJy
Jun 3rd, 2006, 03:58 PM
use:
mySourceArray.CopyTo(myTargetArray, Index);
JenniferBabe
Jun 3rd, 2006, 04:04 PM
use:
mySourceArray.CopyTo(myTargetArray, Index);
Its:
Array.Copy(source, 0, Dest, 0, source.count);
But you have to convert the arrayLists as Arrays. I don't want to convert the ArrayLists to arrays, I want when it is finished copying, the dest and source are still both arraylists.
ComputerJy
Jun 3rd, 2006, 04:10 PM
No, I'm talking about srcArray.CopyTo()
it's not a static method, so you can call it from an instance of the ArrayList
JenniferBabe
Jun 3rd, 2006, 04:31 PM
I'm getting this error:
Argument '2': cannot convert from 'System.Collections.ArrayList' to 'System.Array'
from this code:
Main.CopyTo(0, CopyValue, 0, Main.Count);
where main is the source arraylist and CopyValue is the destination arraylist.
I also tried
Main.CopyTo(CopyValue, 0);
But I was getting the following error
The best overloaded method match for 'System.Collections.ArrayList.CopyTo(System.Array, int)' has some invalid arguments
ComputerJy
Jun 3rd, 2006, 04:35 PM
Sorry, it seems that CopyTo only copies into an array.
use:
ArrayList b=arrayListA.Clone();
This is supposed to work (hopefully)
ComputerJy
Jun 3rd, 2006, 04:37 PM
or you can do this:
arrayListB = arrayListA.GetRange(0, arrayListA.Count);
JenniferBabe
Jun 14th, 2006, 12:16 PM
I got figured it out:
ArrayList al....
add values to al....
call method: method(al)
...
another class:
ArrayList te;
.....
public void method(ArrayList al)
{ // te = al; -> this is wrong since it would copy the actual pointer to al, so
// if I change te, al will also be changed.
te = new ArrayList(al); // This is copy by value only not pointers!
}
Thanks computer jr
jmcilhinney
Jun 14th, 2006, 06:35 PM
You should use the Clone method as cj suggested in post #7. Clone is the standard way to create a shallow copy of an object, assuming that the type implements IClonable, which Clone is a member of.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.