Dynamic array

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Just a stupid question: to work with dynamic array I've to use ArrayList or
is there a way to set the array length in the Array class ?

Thank you.

Keven Corazza
 
ArrayList or anything else from the Collections namespace is what you need
for dynamic growth. Arrays are of fixed capacity and if you need to enlarge
them you must create a larger array and copy the existing elements into it.

Cheers
Daniel
 
Hi Keven,

For dymanic growth of an array you can use the ReDim if you are working with
VB.NET. We have to use the "Preserve" keyword along the ReDim, otherwise the
data in your existing array will be cleared.

Dim arr(3) as String
arr(0)="String1"
ReDim Preserve arr(7)

Here I redefined the size of "arr" to 8 (0-7). But you can use a global
variable of numeric type so as to increase the size dynamically.

Ex. Dim arrSize as Integer - global variable
Dim arr(3) as String
arr(0)="String1"
........................
........................
arrSize = someMethods() that'll return a dynamic value
ReDim Preserve arr(arrSize) - thereby you can set the array length
dynamically.
 
Thet's really, really slow. It copies the entire array to a new array every
time. An ArrayList is far faster and is designed for this type od use.
ReDim was only kept for backward compatibility and should probably never be
used (I can't think of any good reason for it anyway).

-Chris
 
Back
Top