ARRAYS

Visual Basic .NET provides two basic kinds of arrays. First, it provides the normal arrays that you get when you declare a variable by using parentheses. For example, the following code declares an array of Integers named “squares”:

Private Sub ShowSquaresNormalArray()
    Dim squares(10) As Integer
   
    For i As Integer = 0 To 10
        squares(i) = i * i
    Next i
   
    Dim txt As String = ""
    For i As Integer = 0 To 10
        txt &= squares(i).ToString & vbCrLf
    Next i
    MessageBox.Show(txt)
End Sub

The array contains 11 items with indexes ranging from 0 to 10. The code loops over the items, setting each one’s value. Next, it loops over the values again, adding them to a string. When it has finished building the string, the program displays the result.


INITIALIZING ARRAYS
You can initialize an array as in the following code:
Dim fibonacci() As Integer = {1, 1, 2, 3, 5, 8, 13, 21, 33, 54, 87}
If you have Option Infer turned on, you can omit the data type as in the following:
Dim numbers() = {1, 2, 3}
For more information on array initialization, see the section “Initializing Arrays” in Chapter 14, “Data Types, Variables, and Constants.”

The Visual Basic Array class provides another kind of array. This kind of array is actually an object that provides methods for managing the items stored in the array.

The following code shows the previous version of the code rewritten to use an Array object:

Private Sub ShowSquaresArrayObject()
    Dim squares As Array =
        Array.CreateInstance(GetType(Integer), 11)
   
    For i As Integer = 0 To 10
        squares.SetValue(i * i, i)
    Next i
   
    Dim txt As String = ""
    For i As Integer = 0 To 10
        txt &= squares.GetValue(i).ToString & vbCrLf
    Next i
    MessageBox.Show(txt)
End Sub

This version creates the array by using the Array class’s shared CreateInstance method, passing it the data type that the array should contain and the number of items that it should hold. The code then loops over the items using the array’s SetValue method to set the items’ values. If you have Option Strict turned off, the code can set the items’ values exactly as before by using the statement squares(i) = i * i. If Option Strict is on, you need to use SetValue.

Next, the program loops over the items again, using the array’s GetValue method to add the item values to a string. If Option Strict is off, you can use the same syntax as before: txt &= squares(i).ToString & vbCrLf. If Option Strict is on, you need to use the array’s GetValue method. After building the string, the program displays it in a message box as before.

Example program ShowSquares uses similar code to build a list of squares by using a normal array and by using an Array object.

The following sections describe the similarities and differences between normal arrays and Array objects.

Array Dimensions

Both normal variable arrays and Array objects can support multiple dimensions. The following statement declares a three-dimensional array with 11 items in the first dimension, 11 in the second, and 21 in the third. It then sets the value for the item in position (1, 2, 3).

Dim values(10, 10, 20) As Integer
values(1, 2, 3) = 100

The following code does the same thing with an Array object:

Dim values As Array =
    Array.CreateInstance(GetType(Integer), 11, 21, 31)
values.SetValue(100, 1, 2, 3)

If Option Strict is off, the code can use the same syntax for getting and setting the Array item’s value. The following code sets the (1, 2, 3) item’s value to 100 and then displays its value:

Option Strict Off
...
values(1, 2, 3) = 100
Debug.WriteLine(values(1, 2, 3))

Lower Bounds

A normal array of variables always has lower bound 0 in every dimension. The following code declares an array with indexes ranging from 0 to 10:

Dim values(10) As Integer

You can fake a variable array that has nonzero lower bounds, but it requires extra work on your part. You must add or subtract an appropriate amount from each index to map the indexes you want to use to the underlying zero-based indexes.

Array objects can handle nonzero lower bounds for you. The following code creates a two-dimensional array with indexes ranging from 1 to 10 in the first dimension, and 101 to 120 in the second dimension:

Dim dimension_lengths() As Integer = {10, 20}
Dim lower_bounds() As Integer = {1, 101}
Dim values As Array =
    Array.CreateInstance(GetType(Integer), dimension_lengths, lower_bounds)

The code first defines an array containing the number of elements it wants for each dimension (10 in the first dimension and 20 in the second dimension). It then creates an array containing the lower bounds it wants to use for each dimension (the first dimension starts with index 1 and the second dimension starts with index 101).

The code then calls the Array class’s shared CreateInstance method, passing it the data type of the array’s objects, the array of dimension lengths, and the array of lower bounds. The CreateInstance method uses the arrays of lower bounds and dimensions to create an Array object with the appropriate bounds.

Resizing

You can use the ReDim statement to change a normal array’s dimensions. Add the Preserve keyword if you want the array to keep its existing values, as shown here:

Dim values(100) As Integer
...
ReDim Preserve values(200)

An Array object cannot resize itself, but it is relatively easy to copy an Array object’s items to another Array object. The following code creates a values array containing 101 items with indexes ranging from 0 to 100. Later, it creates a new Array object containing 201 items and uses the values array’s CopyTo method to copy its values into the new array. The second parameter to CopyTo gives the index in the destination array where the copy should start placing values.

Dim values As Array =
    Array.CreateInstance(GetType(Integer), 101)
...
Dim new_array As Array =
    Array.CreateInstance(GetType(Integer), 201)
values.CopyTo(new_array, 0)
values = new_array

The Array class’s shared Copy method allows you greater control. It lets you specify the index in the source array where the copy should start, the index in the destination array where the items should be copied, and the number of items to be copied.

Although building a new Array object and copying items into it is more cumbersome than using ReDim to resize a variable array, the process is surprisingly fast.

Speed

There’s no doubt that arrays of variables are much faster than Array objects. In one test, setting and getting values in an Array object took more than 100 times as long as performing the same operations in a variable array.

If your application performs only a few hundred array operations, the difference is unimportant. If your application must access array values many millions of times, you may need to consider using an array of variables even if the Array class would be more convenient for other reasons (such as nonzero lower bounds).

Microsoft has also optimized one-dimensional variable arrays, so they are faster than multidimensional arrays. The difference is much less dramatic than the difference between variable arrays and Array classes, however.

Example program ArraySpeeds, which is available for download on the book’s website, compares the speeds of variable arrays and Array objects. Enter the number of items that you want to use in the arrays and click Go. The program builds one- and two-dimensional arrays and Array objects holding integers. It then fills the arrays and displays the elapsed time.

Figure 25-1 shows the results. Variable arrays are much faster than array classes, and one-dimensional variable arrays generally seem to be slightly faster than two-dimensional arrays.

FIGURE 25-1: Variable arrays are faster than Array classes.

image

Other Array Class Features

The Array class provides several other useful shared methods. For example, the IndexOf and LastIndexOf methods return the position of a particular item in an Array.

Methods such as IndexOf and LastIndexOf would be a strong argument supporting Array objects over normal arrays of variables if it weren’t for one somewhat surprising fact: Those same methods work with regular arrays of variables, too! The following code fills an array of integers and then uses Array methods to display the indexes of the first item with value 6 and the last item with value 3:

Dim values(10) As Integer
For i As Integer = 0 To 10
    values(i) = i
Next i
 
MessageBox.Show(Array.IndexOf(values, 6).ToString)
MessageBox.Show(Array.LastIndexOf(values, 3).ToString)

The following table summarizes some other useful Array class methods.

PROPERTY/METHOD PURPOSE
BinarySearch Returns the index of an item in the previously sorted array. The items must implement the IComparable interface, or you must provide an IComparer object.
Clear Removes all of the items from the array.
ConvertAll Converts an array of one type into an array of another type.
Exists Determines whether the array contains a particular item.
Reverse Reverses the order of the items in the array.
Sort Sorts the items in the array. The items must implement the IComparable interface, or you must provide an IComparer object.

Example program ArrayTests, which is available for download on the book’s website, demonstrates the Array class’s IndexOf, LastIndexOf, Reverse, and BinarySearch methods. It also demonstrates the Sort method for arrays containing integers, objects that implement the IComparable interface, and objects that can be sorted with IComparer objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.9.48