Arrays

From Xojo Documentation

Revision as of 20:03, 8 June 2018 by PLefebvre (talk | contribs) (Created page with "An array is an indexed collection of data for a specific data type. Arrays themselves are not a data type, but any data type can be defined as an array using the Dim statement...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

An array is an indexed collection of data for a specific data type. Arrays themselves are not a data type, but any data type can be defined as an array using the Dim statement or as a property.

Usage

Dim arrayName() As dataType

Dim arrayName(size [,size2,...sizeN]) As dataType

Dim arrayName(), arrayNameN() As dataType [= Array(value1, value2, ..., valueN)]

Notes

All arrays are indexed starting at position 0.

Arrays are often created by specifying the upper bound for the array when you Dim it. Because arrays all start at position 0, an array has one more element than the number you use as the upper bound. For example, this creates an array with 5 elements, which you can then access using the index:

Dim aNames(4) As Text
aNames(0) = "Bob"
aNames(1) = "Bill"
aNames(2) = "Ben"
aNames(3) = "Brad"
aNames(4) = "Bart"

Constants can be used when declaring the upper bound of an array:

Const kBound As Integer = 4
Dim aNames(kBound)

You can also create empty arrays that do not specify a size. At run-time, your code can add elements to it or you can choose to ReDim it to a specific size. These are the two ways to create an empty array:

Dim aFirstNames() As Text
Dim aLastNames(-1) As Text

If you try to access an element of an array that does not exist, you will get an OutOfBoundsException. Here are some examples that would raise the exception:

aNames(5) = "Tom" // this exceeds the upper bound of aNames
aFirstName(1) = "Bill" // aFirstName is still empty

Use the methods Append and Insert to add additional elements to arrays. These methods are the only ways to add elements to empty arrays, but they can also be used to extend the size of any single-dimension array.

Multi-Dimensional Arrays

A multi-dimensional array has elements in 2 or more dimensions. A table would be an example of a 2-dimensional array because it has columns and rows.

Most of the array methods are not supported for multi-dimensional arrays.

You declare multi-dimensional arrays by specifying the upper bound for each dimension:

// A 5x5 table
Dim table(4, 4) As Integer
table(1, 3) = 42

Remove All Elements

The fast way to remove all elements from an array is to Redim it as empty like this:

Dim myArray() As Integer
For i As Integer = 1 To 1000
myArray.Append(i)
Next
ReDim myArray(-1)
// myArray is now empty

See Also

Dim, Redim, Array, Dictionary, For Each...Next, ParamArray commands