Concept
Arrays
Description
Arrays are an indexed collection of data for a specific data type. The index of an array begins at zero. The maximum index value is 2,147,483,646. Arrays themselves are not a data type, but any data type can be defined as an array using the Var statement or as a property.
Usage
Var arrayName() As dataType
Var arrayName(size [, size2,...sizeN ]) As dataType
Var arrayName(), arrayNameN() As dataType [ = Array(value1, value2, ..., valueN) ]
Part |
Type |
Description |
---|---|---|
arrayName |
Variable name |
The name of the array. |
size |
Integer |
Optional: The size of the array. Size must be integer literals or integer constants. |
sizeN |
Integer |
Optional: The size of the next dimension of the array if you are creating a multi-dimensional array. |
dataType |
Data type or class |
The data type or class of the array. |
value1...valueN |
values |
Values that match the dataType to add to the array. |
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
item As DataType |
|||
index As Integer, item As DataType |
|||
value1 As DataType, [valueN As DataType] |
|||
ArrayType |
|||
index As Integer |
|||
newSize As Integer |
|||
AddressOf methodName |
|||
Method descriptions
Arrays.Add
Add(item As DataType)
Adds a new element to the end of a one-dimensional array, increasing the size of the array by one. The item must match the data type of the array.
The Add method works with one-dimensional Arrays only.
This example adds a new element to the end of the names array. The new element becomes the last element of the array.
Var names() As String
names.Add("Betty")
Arrays.AddAt
AddAt(index As Integer, item As DataType)
Adds a new element into an array at the specified index.
The AddAt method works with one-dimensional Arrays only.
Consider the array names defined as follows:
names = Array("Leonard", "Abraham", "Herbert")
The statement:
names.AddAt(2, "Bill")
Because the index of an array begins at zero, the result would be:
Leonard |
Abraham |
Bill |
Herbert |
Arrays.Array
Array(value1 As DataType, [valueN As DataType])
Assigns a list of values to consecutive elements of a one-dimensional array.
The following statements initialize the array using separate assignment statements for each array element:
Var names(2) As String
//using separate assignment statements
names(0) = "Fred"
names(1) = "Ginger"
names(2) = "Stanley"
The following statements use the Array function to accomplish the same thing. Note that you don't have to declare the exact size of the array in the Var statement. The Array function will add elements to the array as needed.
The following statement creates and populates the first three elements of the array aNames.
Var names() As String
' using the Array function
names = Array("Fred", "Ginger", "Stanley")
Arrays.Count
Count(Optional index As Integer) As Integer
Returns the number of rows in the array. For multi-dimensional Arrays, the number of rows in a specific dimension will be returned if the dimension is passed.
This example displays the number of rows in the array:
Var days() As String
days() = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
MessageBox("There are " + days.Count.ToString + " days.")
Arrays.FirstIndex
FirstIndex As Integer
Returns the index of the first element of the array.
The FirstIndex function is used to determine the first element of an array. This is especially useful for writing code that loops through Arrays so that you don't have to be aware of whether an array begins at 0 or 1 (they all begin at 0).
This code loops through an array and replaces each occurrence of X in an array with Y.
For i As Integer = names.FirstIndex To names.LastIndex
If names(i) = "X" Then
names(i) = "Y"
End If
Next
Arrays.IndexOf
IndexOf(item As DataType, Optional startIndex As Integer) As Integer
Used to search for a value in an array. Returns the index of the array element that contains the matching value. Arrays are zero-based.
IndexOf is not case-sensitive, but it is encoding-sensitive.
This example uses a ComboBox that has five items in its pop-up menu that have the names of the workdays of the week. The selected day is in its Text property. This example returns the index of the array element that matches the menu selection.
Var days() As String
days() = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
Var dayNumber As Integer
dayNumber = days.IndexOf(ComboBox1.Text)
If dayNumber = -1 Then
MessageBox("You didn't enter the name of any weekday.")
Else
MessageBox("You entered day number " + dayNumber.ToString)
End If
Arrays.LastIndex
LastIndex(Optional dimension As Integer) As Integer
Returns the index of the last element in the array. The optional parameter allows you to get the last index of a specific dimension if the array is multi-dimensional.
For multi-dimensional Arrays, LastIndex returns the index of the last element of the dimension you specify, or, if you do not specify a dimension, it returns the value for the first dimension. The first dimension is numbered 1.
This code replaces each occurrence of X in an array with Y.
For i As Integer = names.FirstIndex To names.LastIndex
If names(i) = "X" Then
names(i) = "Y"
End If
Next
The following code returns -1 because the newly-declared array has no elements:
Var i() As Integer
Var j As Integer
j = i.LastIndex
The following code of a 2-dimensional array returns 5 in the variable i and 3 in the variable j (remember that the first dimension is numbered 1).
Var i, j As Integer
Var aNames(5, 3) As String
i = aNames.LastIndex
j = aNames.LastIndex(2)
Arrays.Pop
Pop As ArrayType
Removes the last element from an array and returns its value.
The Add and Pop methods can be used together to treat an array as a stack. The Add method pushes a new element onto the array/stack and the Pop method removes the last element from the array/stack and returns its value.
The type of the value returned is the same type as the array.
If array has no values then an OutOfBoundsException is raised.
This example pushes "One", "Two", "Three" onto an array used as a stack and then Pops the values off in reverse order:
Var stack() As String
stack.Add("One")
stack.Add("Two")
stack.Add("Three")
MessageBox(stack.Pop) ' Three
MessageBox(stack.Pop) ' Two
MessageBox(stack.Pop) ' One
This is a directory-crawling routine that performs a depth-first traversal without using recursion:
Var itemsToInspect(0) As FolderItem
Var item As FolderItem
Var folder As FolderItem
folder = FolderItem.ShowSelectFolderDialog
If folder.Exists Then
itemsToInspect(0) = folder
While itemsToInspect.LastRowIndex >= 0
item = itemsToInspect.Pop
If item.IsFolder Then
For Each file As FolderItem In item.Children
itemsToInspect.Add(file)
Next
End If
Wend
End If
Arrays.RemoveAll
RemoveAll
Removes all elements in the array.
Arrays.RemoveAt
RemoveAt(index As Integer)
Removes the specified element from the array.
The RemoveAt method removes the index element from the array. The remaining elements are shifted down to the removed element so that there are no gaps in the array.
The RemoveAt method works with one-dimensional Arrays only.
This example removes element 1 from the aNames array:
Var names() As String = Array("Bob", "Tom", "Jane")
names.RemoveAt(1)
' names() = "Bob", "Jane"
Arrays.ResizeTo
ResizeTo(newSize As Integer)
Resizes the array to the specified index.
The ResizeTo method is used to increase or reduce the number of rows in the array specified. Arrays are zero-based (the first element is zero) so you resize the array using a number that is one less than the number of elements you actually want. The number of parameters passed is the number of dimensions of the array being resized.
When you resize an array to -1, all rows are removed. It is faster to resize an array in this manner than to loop through the array and individually remove each row. You can use the array AddRow or AddAt methods to add rows or you can resize it again to the exact size you need.
When you ResizeTo an array to increase its size, any existing values in the array are retained.
When you resize an array to decrease its size, existing values are retained if they are still within the new array bounds.
This example reduces the aNames array to 11 elements.
aNames.ResizeTo(10)
This example adds 10 elements to the aNames array
aNames.ResizeTo(aNames.LastIndex + 10)
This example reduces the aPeople array to 11 elements for the first dimension and 6 elements for the second dimension
aPeople.ResizeTo(10, 5)
When you resize an array with no bounds, its elements are removed. This is a fast way to clear out an array:
aNames.ResizeTo(-1)
Arrays.Shuffle
Shuffle
Shuffles (rearranges randomly) the elements of an array.
Shuffle works on Arrays of any data type and any number of dimensions. It is based on a random number. An element of the original array has a roughly equal chance of appearing in any cell of the array after the shuffle, regardless of the size and number of dimensions of the array.
A Fisher-Yates shuffle is used. There is no ability to control the seed.
Shuffle a one-dimensional array:
Var values() As Integer = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
values.Shuffle
Var result As String
For i As Integer = 0 To values.LastRowIndex
result = result + i.ToString
Next
Shuffle a two-dimensional array:
Var myArray(5, 5) As String
For i As Integer = 0 To 5
For j As Integer = 0 To 5
myArray(i, j) = i.ToString + j.ToString
Next
Next
myArray.Shuffle
Arrays.Sort
Sort
Sorts the elements of a one-dimensional array in ascending order.
You can only use Sort with one-dimensional arrays. This signature works with the following data types: Single, Double, Integer (and all related Integer types) and String. String sorting is case-insensitive.
Note
When sorting strings, because a character with a diacritical (é for example) is not a difference in case, they are not grouped with the same character minus the diacritical.
If you need to sort some other data type, use the other Sort signature (below) that takes a delegate.
Tip
You can get the equivalent of a descending sort by sorting the array and then accessing it in reverse order with a For Loop using the DownTo keyword.
This example sorts the aNames array.
Var names() As String = Array("Jim", "Bob", "Jane")
names.Sort
' names = "Bob", "Jane", "Jim"
' For a descending sort, access the array in reverse order
Var reverseNames() As String
For i As Integer = names.LastRowIndex DownTo 0
reverseNames.Add(names(i))
Next
' reverseNames = "Jim", "Jane", "Bob"
Arrays.Sort
Sort(AddressOf methodName)
Sorts the elements of a one-dimensional array in ascending order using the method whose address is passed.
Sort an array of DateTimes using a Delegate:
Function DateCompare(value1 As DateTime, value2 As DateTime) As Integer
' This assumes the array is populated with non-Nil dates
If value1.SecondsFrom1970 > value2.SecondsFrom1970 Then Return 1
If value1.SecondsFrom1970 < value2.SecondsFrom1970 Then Return -1
Return 0
End Function
Var myArray() As DateTime
myArray.Add(DateTime.Now)
myArray.Add(New DateTime(2015, 8, 1))
myArray.Add(New DateTime(2014, 4, 1))
myArray.Add(New DateTime(2016, 11, 1))
myArray.Sort(AddressOf DateCompare)
' The array is now sorted
Arrays.SortWith
SortWith(array1 As Array, [arrayN As Array])
Sorts one or more additional Arrays in the same order as the base array. The sort is in ascending order.
Tip
You can get the equivalent of a descending sort by sorting the array and then accessing it in reverse order with a For Loop using the DownTo keyword.
The base array used with the SortWith method works with Integer (and related types), String, String, Single, and Double Arrays only. It accepts only one-dimensional Arrays and it should have unique values. Results are undefined when the elements of the base array are not unique, i.e., elements of the base array are all of the same integer value.
SortWith is ideal for sorting all the columns of a data table by one of its columns. For example, if you have a set of three Arrays that store Names, Addresses, and Phone numbers of a group of people, you can sort the data table by Name by specifying the Names array as the base array and pass the Address and Phone number Arrays as the parameters.
Sort two related Arrays:
Var names() As String = Array("Mozart", "Bing", "Jackson", "Flintstone")
Var zips() As String = Array("04101", "04240", "04123", "04092")
names.SortWith(zips)
' names() = "Bing", "Flintstone", "Jackson", "Mozart"
' zips = "04240", "04092", "04123", "04101"
Sort an array of objects using one of its values:
' Person is a class containing a LastName property
' Assume there is an array called People() As Person that contains
' a collection of Person objects
' Save the last names into their own array
Var lastNames() As String
For i As Integer = 0 To People.LastRowIndex
lastNames.Add(People(i).LastName)
Next
' Now sort the last names and provide the people array
lastNames.SortWith(People)
' The People array is now sorted to match the last names
Notes
Arrays can have a maximum index value of 2,147,483,646 for both 32-bit and 64-bit apps. In addition, although the methods Count, FirstIndex, IndexOf and LastIndex all indicates they return an Integer, they technically return an Int32 (even with 64-bit app). If you are creating Extension methods on Integer you should keep this in mind as you may also want to create Int32 extension methods as well.
Arrays are treated as objects so be aware that assigning an array to another variable or passing an array as a parameter does not make a copy of the array. Instead you get a new variable that points to the original array so any changes you make to the "2nd" array also affects the first array. If you need an actual copy of the array you will have to manually copy its values using a loop.
Arrays are often created by specifying the size of the array when you create it. Because Arrays all start at position 0, an array has one more element than the number you use as the size. For example, this creates an array with 5 elements, which you can then access using the index:
Var aNames(4) As String
aNames(0) = "Bob"
aNames(1) = "Bill"
aNames(2) = "Ben"
aNames(3) = "Brad"
aNames(4) = "Bart"
One way to avoid having to remember that Arrays start at zero is to use the FirstIndex and LastIndex methods.
Constants can be used when declaring the size of an array:
Const kBound As Integer = 4
Var aNames(kBound)
You can also create empty Arrays that do not specify a size. An empty array has a size of -1. At runtime, your code can add elements to it or you can choose to make it a specific size by using ResizeTo. These are the two ways to create an empty array:
Var aFirstNames() As String
Var aLastNames(-1) As String
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 Add and AddAt 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.
Iterating through an array
If you need to access each element of an array but don't need to know the index of that element, you can use an iterator:
Var people() As String = Array("John", "Sally", "Fred", "Nancy")
For Each name As String In People
MessageBox(name)
Next
You can also cycle through an array by index:
Var people() As String = Array("John", "Sally", "Fred", "Nancy")
For index As Integer = 0 To people.LastIndex
Var name As String = people(index)
MessageBox(name)
Next
There is no real advantage to caching the array's last index in a variable to use in a loop. Over millions of iterations, it will only save a few milliseconds.
If the array is stored in a variant, you must cast the variant as an array in order to access it.
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 size for each dimension:
' A 5x5 table
Var table(4, 4) As Integer
table(1, 3) = 42
Remove all elements
The fast way to remove all elements from an array is to use RemoveAll:
Var myArray() As Integer
For i As Integer = 1 To 1000
myArray.Add(i)
Next
myArray.RemoveAll
' myArray is now empty
Objects in arrays
Arrays of objects work like other Arrays except you'll have to deal with possible Nil values just as you would with objects that are not in an array.
If the array index is valid and its value is Nil and you try to use the value, then you get a NilObjectException, just as you would if you try to use any non-array value that is Nil.
If an array index is not valid then that's an OutOfBoundsException and is not related to anything being Nil.
Compatibility
All project types on all supported operating systems.
See also
Array, Var, For Each...Next, ParamArray commands; Dictionary class; Collections of Data topic