Maybe as stupid question

  • Thread starter Thread starter Nikolay Petrov
  • Start date Start date
N

Nikolay Petrov

I have an arraylist. In specific intervals of time I want to get the
data from this array list, clear it, and start putting new data in it.
But I run into problem.
Me code:

Dim ar1 as New ArrayList
' Code to add items to ar1
Dim ar2 as New ArrayList
ar2 = ar1
ar1.Clear
At this point the ar2 also is cleared. Why, and how to prevent?
 
Nikolay Petrov said:
I have an arraylist. In specific intervals of time I want to get the
data from this array list, clear it, and start putting new data in it.
But I run into problem.
Me code:

Dim ar1 as New ArrayList
' Code to add items to ar1
Dim ar2 as New ArrayList
ar2 = ar1

This assignment will make 'ar1' /and/ 'ar2' point to the same instance of
'ArrayList'. Notice that 'As New' for 'ar2' does not make sense because the
instance that is created will be released to the Garbage Collector for
collection after assigning 'ar1' to 'ar2'. The important point is that
variables of a reference type ('ArrayList' is a reference type) "are" not
objects, but /point/ to objects. Multiple variables can point to the same
object.
ar1.Clear
At this point the ar2 also is cleared. Why, and how to prevent?

Use the code below instead:

\\\
Dim al1 As New ArrayList
al1.Add("Bla")
al1.Add("Goo")
Dim al2 As ArrayList = al1.Clone()
al1.Clear()
MsgBox(CStr(al2.Count))
///
 
Nikolay Petrov said:
Dim ar1 as New ArrayList
Dim ar2 as New ArrayList
ar2 = ar1

ArrayLists are Objects, so whenever you create a variable
"containing" one, (like ar1 and ar2, above), you are actually create a
(Object Reference) variable that (dare I say it) "points" to the /actual/
object. Assigning one object reference variable to another simply copies
the "Pointer", not the actual object (which might be *huge*).

You'll need to copy all the values from one ArrayList into the other;
there's probably a built-in method to do it ...

HTH,
Phill W.
 
After the statement 'ar2 = ar1', both variables reference the same object.

Instead. try:

ar2.AddRange( ar1.ToArray( ) )
 

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

Back
Top