Make copy of arraylist

T

tshad

How do you easily make a copy of an arraylist?

If you do:

arrayList2 = arrayList1

You get a pointer so that if you clear arrayList2 (arrayList2.Clear) -
arrayList1 is also cleared.

I want to create a copy of the arrayList, which I can do looping through the
arrayList1 and adding to arrayList2, but is there an easier way to do this?

Thanks,

Tom
 
T

tshad

Apparently, there are 2 methods: Clone and CopyTo.

What is the difference between the 2?

Clone is supposed to do a "shallow copy"? What is that and why is it
different than CopyTo?

Thanks,

Tom
 
R

rowe_newsgroups

Since Mr. Balena says it better than me....

<copyrighted_material>

"The Clone method can create either a shallow copy or a deep copy of
the object. A shallow copy creates only a copy of the object in
question; it doesn't make copies of secondary objects referenced by
it." - From Francesco Balena's book "Programming Microsoft Visual Basic
..NET"

</copyrighted_material>

Thanks,

Seth Rowe
 
G

Guest

CopyTo inserts a copy of the elements in an array into a second array. Once
copied the elements in both arrays are separte but equal.

Heres some code that demonstrates CopyTo in acton:

' Instantiate and intialize the values of a String array named array1.
Dim array1(2) As String
array1 = {"bread", "soup", "beans"}

' Show the values of array1.
For i As Integer = 0 To array1.GetUpperBound(0)
MessageBox.Show(array1(i).ToString)
Next

' Instantiate a String array named array2.
Dim array2(2) As String
' Copy the elements of array1 to array2.
array1.CopyTo(array2, 0)

' Change the first element of array1.
array1(0) = "Was bread, now desert"

' Display the values of array1 and array 2 to show
' they are two separate arrays.
For i As Integer = 0 To array2.GetUpperBound(0)
MessageBox.Show("Array1's element " & i.ToString & " contains '"
& _
array1(i).ToString & "' // Array2's element " & i.ToString & "
contains '" & _
array2(i).ToString & "'")
Next
 
R

RobinS

Seth,
Isn't that a great book? I read it cover to cover.
Have you seen his other one, on Standard Practices?
It has a lot of neat tricks and helpful information
in it, too.
Robin S.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top