Visual Basic 2008 9.0 .NET Examples and Ebook

Arrays

Vorig Onderwerp

Introduction to Visual Basic

|

Procedures and Functions

Volgend Onderwerp

Dynamical Arrays

Vorig Onderwerp

Multidimensional Arrays

|

Array Initializers and For Each Next

Volgend Onderwerp
ReDim Statement

ReDim Statement

ReDim Preserve

ReDim Preserve

Exercise

Exercise

Sensible Enlargements of Arrays

Sensible Enlargements of Arrays



ReDim Statement


When an array variable needs to be declared without knowledge about the number of elements ( the array needs to contain ), the upperbound can be left out.


Module Example1
    Sub Main()
        Dim row() As Integer
        Dim matrix(,) As Integer        ' (1)
        '
        'row(5) = 5                     ' (2) impossible, no array instance
        'matrix(5, 5) = 5               ' (3) impossible, no array instance
        '
        ReDim row(9)                    ' (4)
        ReDim matrix(9, 9)              ' (5)
        '
        row(5) = 5
        matrix(5, 5) = 5
        '
        Console.WriteLine(row(5))
        Console.WriteLine(matrix(5, 5))
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 5
 5

When no upperbound are used within the declaration of an array variable, no array instance exists. So it is impossible to address elements of this - non-existing - array ( lines (2) and (3) ). An NullReferenceException would occur if you tried it anyway.

All arraytypes ( including the above Integer() and Integer(,) ) are referencetypes. This implies that the content of a array variable is either Nothing or a reference to an array instance. Array variables never contain the array(instance), but rather hold a reference to the array(instance).

When an upperbound is used within the declaration of an array variable, an array instance is created with that number ( upperbound - 1 ) of elements. The reference of the array instance is then stored in the variable that is being declared.

When no upperbound is used within the declaration of an array variable, no array instance is created, and the array variable simply contains Nothing.

Nothing in Visual Basic is also called Null in .NET.

The array variables ( row and matrix ) are useless until we make sure they point to an array. We can ReDim to change the number of elements of an array ( lines (4) and (5) ). ReDim actually creates an new array instance, and stores the reference ( of that new instance ) in the array variable used in the ReDim statement.


 ReDim identifier(first-upperbound, second-upperbound, ...)

Declaration :


 Dim matrix(,) As Integer

can also be done by


 Dim matrix As Integer(,)

The parentheses ( without upperbound ) can follow the identifier or the datatype of the elements. When upperbounds are used within the declaration, the parentheses ( with upperbounds ) must follow the identifier.

Next example declares an two-dimensional array with 3 rows and 4 columns, to later change the dimensions to 6 rows and 10 columns.


Module Example2
    Sub Main()
        Dim matrix(2, 3) As Integer
        '
        matrix(1, 1) = 10
        Console.WriteLine(matrix(1, 1))
        '
        ReDim matrix(5, 9)
        Console.WriteLine(matrix(1, 1))                                    ' (1)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 10
 0

Notice ( line (1) ) how all elements will contain the default value of the element type after a normal ReDim statement. Line (1) results in 0 and not in the old value 10.

ReDim can only change the number of elements of the dimensions, but can not change the number of dimensions or the datatype of the elements, these were defined in the declaration, and are unchangeable.


Klik hier om terug naar boven te gaan.  Up



ReDim Preserve


When you want to change the number of elements of an array, but preserve the values of that array, ReDim Preserve can be used ( line (1) ).

This will also create an new array instance, but all values ( that fit within the new array ) will be copied to that new array instance.


Module Example3
    Sub Main()
        Dim matrix(2, 3) As Integer
        '
        matrix(1, 1) = 10
        Console.WriteLine(matrix(1, 1))
        '
        ReDim Preserve matrix(2, 9)                                        ' (1)
        Console.WriteLine(matrix(1, 1))                                    ' (2)
        '
        ReDim Preserve matrix(5, 9)                                       ' (3)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 10
 10

Notice the output of line (2), which results in 10 and not 0, which would be the result of a normal ReDim.

A limitation of ReDim Preserve is that only the number of elements of the last dimension can be changed. Line (3) would result in a runtime error ArrayTypeMismatchException.

Needless to say that ReDim Preserve is quite a "heavy" ( time and memory consuming ) operation. Not only does the ReDim Preserve has to create an new array instance ( like any ReDim would do, even without Preserve ), but it also needs to copy the old values to the new instance.
The more elements the array ( to ReDim ) contains, the "heavier" the operation is.


Klik hier om terug naar boven te gaan.  Up



Exercise


Task :

Create a program to manage the names of employees and the departments they work in.

Use only 1 two-dimensional array to store the names and departments. Make sure the array never has more elements than strictly necessary.


Output :

 No Employees.
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>a</i>
 Name        : <i>John</i>
 Department : <i>Management</i>
 Employees Overview :
 John ( Management )
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>A</i>
 Name        : <i>Paul</i>
 Department : <i>Marketing</i>
 Employees Overview :
 John ( Management )
 Paul ( Marketing )
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>b</i>
 Employees Overview :
 John ( Management )
 Paul ( Marketing )
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>r</i>
 Employees Overview :
 John ( Management )
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>R</i>
 No Employees.
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>a</i>
 Name        : <i>Jane</i>
 Department : <i>Management</i>
 Employees Overview :
 Jane ( Management )
 MENU : <a> Add Employee / <r> Remove Last Employee / <x> Exit : <i>X</i>

Solution :


Module Exercise1Solution
    Sub Main()
        Dim menu As Char
        Dim employees As String(,)
        Dim count As Integer
        Dim index As Integer
        Do Until menu = "x"c OrElse menu = "X"c
            If count > 0 Then
                Console.WriteLine("Employees Overview :")
                For index = 0 To count - 1
                    Console.WriteLine(employees(0, index) & _
                                      " (" & employees(1, index) & ")")
                Next
            Else
                Console.WriteLine("No Employees.")
            End If
            Console.Write("MENU : <a> Add Employee / " & _
                          "<r> Remove Last Employee / " & _
                          "<x> Exit : ")
            menu = Console.ReadLine()
            Select Case menu
                Case "a"c, "A"c
                    ReDim Preserve employees(1, count)
                    Console.Write("Name        : ")
                    employees(0, count) = Console.ReadLine()
                    Console.Write("Department : ")
                    employees(1, count) = Console.ReadLine()
                    count += 1
                Case "r"c, "R"c
                    If count > 0 Then
                        ReDim Preserve employees(1, count - 1)
                        count -= 1
                    End If
                Case "x"c, "X"c
                    ' doe niets
            End Select
        Loop
    End Sub
End Module
Download Broncode

Klik hier om terug naar boven te gaan.  Up


Sensible Enlargements of Arrays


When a large collection needs to be managed, one could initially create an array with sufficient elements. By doing this we avoid using the rather "heavy" ReDim Preserve operation when elements needs to be added.
The disadvantage would be that lot of many memory ( probably to many memory ) is used.

A good alternative - often used - is to work with a growing capacity. When the limits of the capacity are reached, the capacity doubles.
Doing this, we avoid wasting to many memory, and restrict the number of ReDim Preserves.


Module Example4
    Sub Main()
        Dim capacity As Integer = 2
        Dim count As Integer
        Dim numbers(capacity - 1) As Integer
        '
        Do
            Dim index As Integer
            Console.Write("Numbers ( capacity " & capacity & _
                          ", count " & count & " ) : ")
            For index = 0 To count - 1
                Console.Write(numbers(index) & " ")
            Next
            Console.WriteLine()
            Console.Write("Number ? : ")
            Dim number As Integer = Console.ReadLine()
            count += 1
            If count > capacity Then
                capacity *= 2
                ReDim Preserve numbers(capacity - 1)
            End If
            numbers(count - 1) = number
        Loop
    End Sub
End Module
Download Broncode

Output :

 Numbers ( capacity 2, count 0 ) :
 Number ? : <i>1</i>
 Numbers ( capacity 2, count 1 ) : 1
 Number ? : <i>2</i>
 Numbers ( capacity 2, count 2 ) : 1 2
 Number ? : <i>3</i>
 Numbers ( capacity 4, count 3 ) : 1 2 3
 Number ? : <i>4</i>
 Numbers ( capacity 4, count 4 ) : 1 2 3 4
 Number ? : <i>5</i>
 Numbers ( capacity 8, count 5 ) : 1 2 3 4 5
 Number ? : <i>6</i>
 Numbers ( capacity 8, count 6 ) : 1 2 3 4 5 6
 Number ? : <i>7</i>
 Numbers ( capacity 8, count 7 ) : 1 2 3 4 5 6 7
 Number ? : <i>8</i>
 Numbers ( capacity 8, count 8 ) : 1 2 3 4 5 6 7 8
 Number ? : <i>9</i>
 Numbers ( capacity 16, count 9 ) : 1 2 3 4 5 6 7 8 9
 Number ? :




This version ( published on 2008-06-24 ) is printed from http://www.studyvb.com, visit the website for more recent information.

Updated On : 2008-01-24

Download Broncode

Published On : 2008-06-24

Dynamical Arrays

Vorig Onderwerp

Multidimensional Arrays

|

Array Initializers and For Each Next

Volgend Onderwerp

Arrays

Vorig Onderwerp

Introduction to Visual Basic

|

Procedures and Functions

Volgend Onderwerp
Nederlands  Nederlands

Add to favorites (IE).