Section 26.3. Class Array and Enumerators


26.3. Class Array and Enumerators

Chapter 8 presented basic array-processing capabilities. All arrays implicitly inherit from the MustInherit class Array (namespace System). Array operty Length specifies the number of elements in the array. In addition, class Array provides Shared methods that provide algorithms for processing arrays. Typically, class Array overloads these methodsfor example, Array method Reverse can reverse the order of the elements in an entire array or can reverse the elements in a specified range of elements in an array. For a complete list of class Array's Shared methods, visit:

msdn2.microsoft.com/en-us/library/system.array.aspx

Figure 26.3 demonstrates several Shared methods of class Array.

Figure 26.3. Array class used to perform common array manipulations

  1  ' Fig. 26.3: UsingArray.vb  2  ' Array class Shared methods for common array manipulations.,  3  Imports System.Collections  4  5  Module UsingArray  6     Private integerValues As Integer () = {1, 2, 3, 4, 5, 6}  7     Private doubleValues As Double() = {8.4, 9.3, 0.2, 7.9, 3.4}  8     Private integerValuesCopy As Integer()  9 10     Sub Main() 11        ' defaults to zeroes 12        integerValuesCopy = New Integer (integerValues.Length 1) {} 13 14        Console.WriteLine("Initial array values:" & vbCrLf) 15        PrintArrays() ' output initial array contents 16 17        ' sort doubleValues 18        Array.Sort(doubleValues) 19 20        ' copy integerValues into integerValuesCopy 21        Array.Copy(integerValues, integerValuesCopy, integerValues.Length) 22 23        Console.WriteLine(vbCrLf & _ 24           "Array values after Sort and Copy:" & vbCrLf) 25        PrintArrays() ' output array contents 26        Console.WriteLine() 27 28        ' search for 5 in integerValues 29        Dim result  As Integer  = Array.BinarySearch(integerValues, 5) 30 31        If (result >= 0)  Then 32           Console.WriteLine("5 found at element {0} in integerValues", _ 33              result) 34        Else 35           Console.WriteLine("5 not found in integerValues") 36        End If 37 38        ' search for 8763 in integerValues 39        result = Array.BinarySearch(integerValues, 8763) 40 41        If (result >= 0)  Then 42           Console.WriteLine("8763 found at element {0} in integerValues", _ 43              result) 44        Else 45          Console.WriteLine("8763 not found in integerValues") 46        End If 47     End Sub ' Main 48 49     ' output array content with enumerators 50     Private Sub PrintArrays() 51        Console.Write("doubleValues: ") 52 53        ' iterate through the  Double array with an enumerator 54        Dim enumerator As IEnumerator = doubleValues.GetEnumerator() 55         56        While (enumerator.MoveNext())                                57           Console.Write(enumerator.Current & " ")                   58        End While                                                    59 60        Console.Write(vbCrLf & "integerValues: ") 61 62        ' iterate through the  integer array with an enumerator 63        enumerator = integerValues.GetEnumerator() 64         65        While (enumerator.MoveNext())              66           Console.Write(enumerator.Current & " ") 67        End While                                  68 69        Console.Write(vbCrLf & "integerValuesCopy: ") 70 71        ' iterate through the second integer array with a For Each statement 72        For Each element As Integer In integerValuesCopy 73           Console.Write(element & " ")                 74        Next, element                                    75 76        Console.WriteLine() 77     End Sub ' PrintArrays 78  End Module ' UsingArray 

 Initial array values: doubleValues: 8.4 9.3 0.2 7.9 3.4 integerValues: 1 2 3 4 5 6 integerValuesCopy: 0 0 0 0 0 0 Array values after Sort and Copy: doubleValues: 0.2 3.4 7.9 8.4 9.3 integerValues: 1 2 3 4 5 6 integerValuesCopy: 1 2 3 4 5 6 5 found at element 4 in integerValues 8763 not found in integerValues 



The Imports statement in line 3 enables us to use the classes and interfaces of namespace System.Collections (such as interface IEnumerator, which we discuss shortly). A reference to the assembly for this namespace is implicitly included in every application, so we do not need to add any new references to the project file. Class Array is in namespace System, which is implicitly imported.

Our test class declares three array variables (lines 68). The first two lines initialize integerValues and doubleValues to an Integer and Double array, respectively. Variable integerValuesCopy is intended to demonstrate Array's Copy method, so it is declared, but does not yet refer to an array.

Line 12 initializes integerValuesCopy to an Integer array with the same length as array integerValues. Line 15 calls the PrintArrays method (lines 5077) to output the initial contents of all three arrays. We discuss the PrintArrays method shortly. We can see from the output of Fig.26.3 that each element of array integerValuesCopy is initialized to the default value 0.

Line 18 uses Shared Array method Sort to sort array doubleValues. When this method returns, the array contains its original elements sorted in ascending order.

Line 21 uses Shared Array method Copy to copy elements from array integerValues to array intValuesCopy. The first argument is the array to copy (integerValues), the second argument is the destination array (integerValuesCopy) and the third argument is an Integer representing the number of elements to copy (integerValues.Length specifies all elements).

Lines 29 and 39 invoke Shared Array method BinarySearch to perform binary searches on array integerValues. Method BinarySearch receives the sorted array to search and the key for which to search. The method returns the index in the array at which it finds the key (or a negative number otherwise). Note that BinarySearch assumes that it receives a sorted array.

Common Programming Error 26.1

Passing an unsorted array to BinarySearch is a logic errorthe value returned is undefined.


The PrintArrays method (lines 5077) uses class Array's methods to loop though each array. Recall that Array implements the IEnumerable interface. All arrays inherit implicitly from Array, so both the Integer() and Double() array types implement IEnumerable interface method GetEnumerator, which returns an enumerator that can iterate over the collection. In line 54, the GetEnumerator method obtains an enumerator for array doubleValues. Interface IEnumerator (which all enumerators implement) defines methods MoveNext and Reset and property Current. MoveNext moves the enumerator to the next element in the collection. The first call to MoveNext positions the enumerator at the first element of the collection. MoveNext returns true if there is at least one more element in the collection; otherwise, the method returns False. Method Reset positions the enumerator before the first element of the collection. Methods MoveNext and Reset tHRow an InvalidOperationException if the contents of the collection are modified in any way after the enumerator is created. Property Current returns the object at the current location in the collection.

Common Programming Error 26.2

If a collection is modified after an enumerator is created for it, the enumerator immediately becomes invalida method called with the enumerator after this point throws an InvalidOperationException. For this reason, enumerators are said to be "fail fast."


When an enumerator is returned by the GetEnumerator method in line 54, it is initially positioned before the first element in Array doubleValues. Then, when line 56 calls MoveNext in the first iteration of the loop, the enumerator advances to the first element in doubleValues. The loop in lines 5658 iterates over the elements until the enumerator passes the end of doubleValues and MoveNext returns False. Each iteration of the loop uses the enumerator's Current property to obtain and output the current array element. Lines 6367 iterate over array integerValues.

Note that PrintArrays is called twice (lines 15 and 25), so GetEnumerator is called twice on doubleValues. The GetEnumerator method (lines 54 and 63) always returns an enumerator positioned before the first element. Also note that the IEnumerator property Current is read only. Enumerators cannot be used to modify the contents of collections, only to obtain the contents.

The For Each statement in lines 7274 iterates over the collection elements. The For Each statement implicitly obtains an enumerator via the GetEnumerator method of a collection and uses the enumerator's MoveNext method and Current property to traverse the collection, just as we did explicitly in lines 5458 and lines 6367. For this reason, we can use the For Each statement to iterate over any collection that implements the IEnumerable interfacenot just arrays. We demonstrate this functionality in the next section when we discuss class ArrayList.

Other Shared Array methods include Clear (to set a range of elements to 0 or Nothing), CreateInstance (to create a new array of a specified type), IndexOf (to locate the first occurrence of an object in an array or portion of an array), LastIndexOf (to locate the last occurrence of an object in an array or portion of an array) and Reverse (to reverse the contents of an array or portion of an array).




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net