An array is an indexed collection of objects, all of the same type. Arrays are both built into the language and implemented as types, with properties, fields, and methods.
Visual Basic 2005 provides native syntax for the declaration of Arrays. What is actually created, however, is an object of type System.Array . Arrays in Visual Basic 2005 provide you with the best of both worlds: easy-to-use array syntax underpinned with an actual class definition, so that instances of an array have access to the methods and properties of System.Array. These appear in Table 17-1.
17.1.1. Declaring ArraysDeclare a Visual Basic 2005 array with the following syntax: Dim array-name( ) as type For example: Dim intArray( ) as Integer
The parentheses tell the Visual Basic 2005 compiler that you are declaring an array, and the type specifies the type of the elements it will contain. In the previous example, intArray is an array of integers. You instantiate an array using the new keyword. For example: intArray = new Integer(5) { }
The effect of this declaration is to create and intialize an array of six integers, all of which are initialized to the value zero.
It is important to distinguish between the array itself (which is a collection) and the elements of the array. intArray is the array (or, more accurately, the variable that holds the reference to the array); its elements are the six integers it holds. Visual Basic 2005 arrays are reference types, created on the heap. Thus, the array to which intArray refers is allocated on the heap. The elements of an array are allocated based on their own type. Since Integers are value types, the elements in intArray will be value types, not boxed integers, and, thus, all the elements will be created inside the block of memory allocated for the array. The block of memory allocated to an array of reference types will contain references to the actual elements, which are themselves created on the heap in memory separate from that allocated for the array. 17.1.2. Understanding Default ValuesWhen you create an array of value types, each element initially contains the default value for the type stored in the array. The statement: intArray = new Integer(5) { } creates an array of six integers, each of whose value is set to 0, which is the default value for integer types. On the other hand reference types in an array are not initialized to their default value. Instead, the references held in the array are initialized to null. If you attempt to access an element in an array of reference types before you have specifically initialized the elements, you will generate an exception. Assume you have created a Button class. Declare an array of Button objects with the following statement: Dim myButtonArray( ) as Button and instantiate the actual array like this: myButtonArray = new Button(3) You can shorten this to: Dim myButtonArray( ) as Button = new Button(3) This statement does not create an array with references to four Button objects. Instead, this creates the array myButtonArray with four null references. To use this array, you must first construct and assign the four Button objects, one for each reference in the array. 17.1.3. Accessing Array ElementsAccess the elements of an array using the index operator (( )). Arrays are zero-based, which means that the index of the first element is always zero in this case, myArray(0). As explained previously, arrays are objects and, thus, have properties. One of the more useful of these is Length, which tells you how many objects are in an array. Array objects can be indexed from 0 to Length-1. That is, if there are five elements in an array; their indices are 0, 1, 2, 3, and 4. Example 17-1 is a console application named Arrays, that illustrates the array concepts covered so far. Example 17-1. Working with ArraysModule Module1 Public Class Employee Private _empID As String Public Sub New(ByVal empID As Integer) Me._empID = empID End Sub Public Overrides Function ToString( ) As String Return _empID End Function End Class Sub Main( ) Dim empArray( ) As Employee empArray = New Employee(3) { } Dim intArray( ) As Integer = New Integer(5) { } For index As Integer = 0 To empArray.Length - 1 empArray(index) = New Employee(index + 5) Next For index As Integer = 0 To intArray.Length - 1 Console.WriteLine(intArray(index).ToString( )) Next For index As Integer = 0 To empArray.Length - 1 Console.WriteLine(empArray(index).ToString( )) Next End Sub End Module Output: 0 0 0 0 0 0 5 6 7 8 The example starts with the definition of an Employee class, which implements a constructor taking a single integer parameter. The ToString( ) method inherited from Object is overridden to print the value of the Employee object's employee ID. The test method declares and then instantiates a pair of arrays. The integer array is automatically filled with integers whose value is set to 0. The Employee array contents must be constructed by hand. Finally, the contents of the arrays are printed to ensure that they are filled as intended. The six integers print their value (zero) first, followed by the four Employee objects. 17.1.4. Initializing Array ElementsIt is possible to initialize the contents of an array at the time it is instantiated by providing a list of values delimited by curly braces ({ }). Visual Basic 2005 provides a longer and a shorter syntax: Dim firstArray( ) As Integer = New Integer(5) {1, 2, 3, 4, 5, 6} Dim secondArray( ) As Integer = {1, 2, 3, 4, 5, 6} There is no practical difference between these two statements, and most programmers will use the shorter syntax. 17.1.5. Multidimensional ArraysArrays can be thought of as long rows of slots into which values can be placed. Once you have a picture of a row of slots, imagine 10 rows, one on top of another. This is the classic two-dimensional array of rows and columns (often referred to as a Matrix).[*]
A third dimension is possible, but somewhat harder to imagine. Okay, now imagine four dimensions. Now imagine 10. Those of you who are not string-theory physicists have probably given up, as have I. Multidimensional arrays are useful, however, even if you can't quite picture what they would look like. Visual Basic 2005 supports two types of multidimensional arrays: rectangular and jagged. In a rectangular array, every row is the same length. A jagged array, however, is an array of arrays, each of which can be a different length. 17.1.5.1. Rectangular arraysA rectangulararray is an array of two (or more) dimensions. In the classic two- dimensional array, the first dimension is the rows and the second dimension is the columns. To declare a two-dimensional array, use the following syntax: Dim identifier(,) As type For example, to declare and instantiate a two-dimensional rectangular array named theMatrix that contains four rows and three columns of integers, you would write: Dim theMatrix(,) As Integer = New Integer(3,2) { } Example 17-2 declares, instantiates, initializes, and prints the contents of a two- dimensional array. In this example, a nested For loop is used to initialize the elements of the array. Example 17-2. theMatrixModule Module1 Sub Main( ) Const rows As Integer = 3 Const columns As Integer = 2 Dim theMatrix(,) As Integer = New Integer(rows, columns) { } For index As Integer = 0 To rows For internalIndex As Integer = 0 To columns theMatrix(index, internalIndex) = _ (index + 1) * (internalIndex + 1) Next Next For index As Integer = 0 To rows For internalIndex As Integer = 0 To columns Console.WriteLine("theMatrix({0})({1}) = {2}", _ index, internalIndex, theMatrix(index, internalIndex)) Next Next End Sub End Module Output: theMatrix(0)(0) = 1 theMatrix(0)(1) = 2 theMatrix(0)(2) = 3 theMatrix(1)(0) = 2 theMatrix(1)(1) = 4 theMatrix(1)(2) = 6 theMatrix(2)(0) = 3 theMatrix(2)(1) = 6 theMatrix(2)(2) = 9 theMatrix(3)(0) = 4 theMatrix(3)(1) = 8 theMatrix(3)(2) = 12 In this example, you declare a pair of constant values: Const rows As Integer = 3 Const columns As Integer = 2 that are then used to set the size of the dimensions the array: Dim theMatrix(,) As Integer = New Integer(rows, columns) { } Notice the syntax. The parentheses in the theMatrix(,) declaration indicate that the array has two dimensions. (Two commas would indicate three dimensions, and so on.) The actual instantiation of theMatrix with New Integer(rows, columns) { } allocates the memory and sets the size of each dimension. The program fills the rectangle with a pair of nested For loops, iterating through each column in each row. Thus, the first element filled is theMatrix(0,0), followed by theMatrix(0,1), and theMatrix(0,2). Once this is done, the program moves on to the next rows: theMatrix(1,0), theMatrix(1,1), theMatrix(1,2), and so forth, until all the columns in all the rows are filled. Just as you can initialize a one-dimensional array using lists of values, you can initialize a two-dimensional array using similar syntax. Thus, you can modify the previous example to initialize the values at the same time you declare them: Dim theMatrixReloaded(,) As Integer = New Integer(rows, columns) _ { _ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11} _ } 17.1.6. Jagged ArraysA jaggedarray is an array of arrays. It is called "jagged " because the rows need not be the same size, and thus a graphical representation of the array would not be square. When you create a jagged array, you declare the number of rows in your array. Each row will hold an array, which can be of any length. These arrays must each be declared. You can then fill in the values for the elements in these "inner" arrays. In a jagged array, each dimension is a one-dimensional array. To declare a jagged array, use the following syntax, where the number of parentheses indicates the number of dimensions of the array: Dim identifier( )( ) as type For example, you would declare a two-dimensional jagged array of integers named myJaggedArray as follows: Dim myJaggedArray( )( ) as Integer = new Integer(5) Access the fifth element of the third array by writing myJaggedArray(2)(4). Example 17-3 creates a jagged array named myJaggedArray, initializes its elements, and then prints their content. To save space, the program takes advantage of the integer array elements automatically initializing to zero, and it initializes the values of only some of the elements. Example 17-3. Working with a jagged arrayModule Module1 Sub Main( ) Const rows As Integer = 3 ''declare the jagged array as 4 rows high Dim jaggedArray As Integer( )( ) = New Integer(rows)( ) { } '' the first row has 3 elements jaggedArray(0) = New Integer(2) { } '' the second row has 2 elements jaggedArray(1) = New Integer(1) { } '' the third row has 4 elements jaggedArray(2) = New Integer(3) { } '' the fourth row has 5 elements jaggedArray(3) = New Integer(4) { } '' fill some (not all) elements of the rows jaggedArray(0)(2) = 15 jaggedArray(1)(1) = 12 jaggedArray(2)(1) = 9 jaggedArray(2)(2) = 99 jaggedArray(3)(0) = 10 jaggedArray(3)(1) = 11 jaggedArray(3)(2) = 12 jaggedArray(3)(3) = 13 jaggedArray(3)(4) = 14 For index As Integer = 0 To jaggedArray(0).Length - 1 Console.WriteLine("jaggedArray(0)(" & index & "): {0}", _ jaggedArray(0)(index)) Next For index As Integer = 0 To jaggedArray(1).Length - 1 Console.WriteLine("jaggedArray(1)(" & index & "): {0}", _ jaggedArray(1)(index)) Next For index As Integer = 0 To jaggedArray(2).Length - 1 Console.WriteLine("jaggedArray(2)(" & index & "): {0}", _ jaggedArray(2)(index)) Next For index As Integer = 0 To jaggedArray(3).Length - 1 Console.WriteLine("jaggedArray(3)(" & index & "): {0}", _ jaggedArray(3)(index)) Next End Sub End Module Output: jaggedArray(0)(0): 0 jaggedArray(0)(1): 0 jaggedArray(0)(2): 15 jaggedArray(1)(0): 0 jaggedArray(1)(1): 12 jaggedArray(2)(0): 0 jaggedArray(2)(1): 9 jaggedArray(2)(2): 99 jaggedArray(2)(3): 0 jaggedArray(3)(0): 10 jaggedArray(3)(1): 11 jaggedArray(3)(2): 12 jaggedArray(3)(3): 13 jaggedArray(3)(4): 14 In this example, a jagged array is created with four rows: Dim jaggedArray As Integer( )( ) = New Integer(rows)( ) { } Notice that the second dimension is not specified. Each row holds an array and each of these arrays can have a different size. Indeed, you see that the first has three rows, the second has two, and so forth. Once an array is specified for each row, you need only populate the various members of each array and then print their contents to ensure that all went as expected.
|