|
|
|
Arrays allow you to refer to a series of variables by the same name and to use a number, called an index or subscript, to tell them apart. This helps you create shorter and simpler code in many situations, because you can set up loops that deal efficiently with any number of elements by using the index number.
Facts about Array data type
- An array can have one dimension or more than one. You can specify up to 32 dimensions, although more than three is extremely rare.
- In VB.net array are contiguous along each dimension from subscript 0 through the highest subscript of that dimension.
- If you don’t specify array size then you can change it later using
ReDim statement.
- In VB.net every type of array is reference type.
- An array variable holds a pointer to the data constituting the elements and the rank and length information.
- All arrays inherit from
System.Array class.
- An array declaration specifies a data type, and all its elements must be of that type.
- When the data type is Object, the individual elements can contain different kinds of data (objects, strings, numbers, and so on).
- You can define array of fundamental datatype(i.e. String, Integer, Boolean ...), Structure or of an object class.
Declaring Array Variables
Array can be declared just like all other variables. You can use Dim statement to declare single/multi dimensional array of any type.
Single-Dimensional Array
The following example declares single dimensional array which can store 5 items of string type. |
Click here to copy the following block | The following example declares 2 dimensional array.
Dim arrPersons(4,2) As String
arrPersons(0,0)="Bob" arrPersons(0,1)="770-334-4445" arrPersons(0,2)="7/1/1970"
arrPersons(1,0)="Tina" arrPersons(1,1)="404-233-5644" arrPersons(1,2)="1/5/1977"
arrPersons(2,0)="Jonny" arrPersons(2,1)="770-899-1999" arrPersons(2,2)="8/13/1971"
arrPersons(3,0)="Kim" arrPersons(3,1)="770-444-2200" arrPersons(3,2)="12/1/1975"
arrPersons(4,0)="Jim" arrPersons(4,1)="770-367-4000" arrPersons(4,2)="11/6/1980" |
Jagged Arrays (Array of Arrays)
This is another type of array supported in VB.net. Sometimes the data in your application is two-dimensional but not rectangular. For example you want to store states and its cities in array.
Example |
Click here to copy the following block | Sub JaggedArrayDemo()
Dim arrStateCities(49)() As String
arrStateCities(0) = New String() {"AL", "Birmingham", "Montgomery", "Mobile", "Huntsville", "Tuscaloosa", "Hoover", "Dothan", "Decatur", "Auburn"} arrStateCities(1) = New String() {"AK", "Anchorage", "Juneau", "Fairbanks", "Sitka", "Ketchikan"} arrStateCities(2) = New String() {"AZ", "Phoenix", "Tucson", "Mesa", "Glendale", "Scottsdale", "Chandler", "Tempe", "Gilbert", "Peoria", "Yuma", "Flagstaff"} arrStateCities(49) = New String() {"WY", "Cheyenne", "Casper", "Laramie", "Gillette"}
Dim statesCnt, citiesCnt As Integer For statesCnt = 0 To UBound(arrStateCities) If Not arrStateCities(statesCnt) Is Nothing Then Console.WriteLine("State [" & arrStateCities(statesCnt)(0) & "] : Total Cities => " & UBound(arrStateCities(statesCnt))) For citiesCnt = 1 To UBound(arrStateCities(statesCnt)) Console.Write(arrStateCities(statesCnt)(citiesCnt) & " ") Next Console.WriteLine(vbCrLf & "================================================") End If Next End Sub |
State [AL] : Total Cities => 9
Birmingham Montgomery Mobile Huntsville Tuscaloosa Hoover Dothan Decatur Auburn
================================================
State [AK] : Total Cities => 5
Anchorage Juneau Fairbanks Sitka Ketchikan
================================================
State [AZ] : Total Cities => 11
Phoenix Tucson Mesa Glendale Scottsdale Chandler Tempe Gilbert Peoria Yuma Flagstaff
================================================
State [WY] : Total Cities => 4
Cheyenne Casper Laramie Gillette
================================================
|
Initializing Arrays
In VB.net you can initialize an array variable as a part of its declaration. There are certain rules which you must follow when you initialize array variable.
- If you want to initialize an array during variable declaration then you can not define array size after variable name. Parenthesis must be empty.
Example |
- If you use New keyword then it must contain "{}" at the end. Only different thing about using New is you can define size in datatype constructor but still I don’t find it useful coz you can initialize array without using New keyword but lets look at the example for more understanding.
Example |
Click here to copy the following block | Dim A1() As Integer = New Integer() {} Dim A2() As Integer = New Integer()
Dim B1() As Integer = New Integer(3) {} Dim B2() As Integer = New Integer(3)
Dim C1() As Integer = New Integer(3){111,222,333,444} Dim C2() As Integer = New Integer(3){111,222} |
Let's look at few examples which will give you more idea.
Initializing single-dimensional array
The following example declares a single dimensional integer array with 5 items. |
The following lines produce error |
If you want to store different types in the same array then you must declare an array of object datatype. Object can hold reference of any type. |
Initializing single-dimensional array
Now let's look at the example which declares a multi dimensional array with initial values. |
Click here to copy the following block | Dim arrPersons(,) As String = {{"Boby", "770-334-4445", "7/11/1970"}, _ {"Tina", "404-233-5644", "1/15/1977"}, _ {"Roni", "334-223-7854", "3/11/1979"}, _ {"Jhon", "770-899-1999", "8/13/1971"}}
Dim arrPersons(,) As String =New String(2,2) {{"Boby", "770-334-4445", "7/11/1970"}, _ {"Tina", "404-233-5644", "1/15/1977"}, _ {"Roni", "334-223-7854", "3/11/1979"}, _ {"Jhon", "770-899-1999", "8/13/1971"}}
Dim arrPersons(,) As String =New String(,) {{"Boby", "770-334-4445", "7/11/1970"}, _ {"Tina", "404-233-5644", "1/15/1977"}, _ {"Roni", "334-223-7854", "3/11/1979"}, _ {"Jhon", "770-899-1999", "8/13/1971"}} |
Resizing Arrays
You can resize an array at any time by assigning a different array object to the same array variable, using either ReDim or a standard assignment statement. The new array object can have different dimensions, although it must retain the same rank. This helps you manage memory efficiently. For example, you can use a large array for a short time and then ReDim it to a smaller size. This frees up memory you no longer need. |
Note: Instead of using regular arrays with ReDim Preserve consider System.Collections.ArrayList class if you need dynamic array functionality. Dynamic arrays can be a major performance pitfall. Under the covers, when you call ReDim Preserve MyArray(5) , VB.NET will actually take the array as it stands before that statement, create a copy of it with the additional positions needed (or a smaller size), then destroy the original copy. This is because there really isn't such a thing as a "dynamic array" in .NET. This is what the System.Collections.ArrayList class was invented for (well, probably for many other reasons too). Check the last section for more info about ArrayList class |
When you ReDim an array, its existing values are normally lost. However, you can retain them by including the Preserve keyword in the ReDim statement. For example, the following statement declares a new string array, initializes its elements from the corresponding elements of the existing MyArray, and assigns the new array to MyArray. Resizing single dimensional array example |
Click here to copy the following block | Dim arrPersons(2) As String
arrPersons(0) = "Bob" arrPersons(1) = "Jim" arrPersons(2) = "Ron"
ReDim Preserve arrPersons(4)
arrPersons(3) = "Kim" arrPersons(4) = "Joe"
ReDim Preserve arrPersons(3) |
Resizing multi dimensional array example |
Click here to copy the following block | Dim arrPersons(4, 0) As String
arrPersons(0, 0) = "Bob" arrPersons(1, 0) = "Tina" arrPersons(2, 0) = "Jonny" arrPersons(3, 0) = "Kim" arrPersons(4, 0) = "Jim"
ReDim Preserve arrPersons(4, 2)
arrPersons(0, 1) = "770-334-4445" arrPersons(0, 2) = "7/1/1970"
arrPersons(1, 1) = "404-233-5644" arrPersons(1, 2) = "1/5/1977"
arrPersons(2, 1) = "770-899-1999" arrPersons(2, 2) = "8/13/1971"
arrPersons(3, 1) = "770-444-2200" arrPersons(3, 2) = "12/1/1975"
arrPersons(4, 1) = "770-367-4000" arrPersons(4, 2) = "11/6/1980" |
Note: ReDim can only change the rightmost dimension for multi dimensional array so if you declare your array of 5x3x4 size then you can not change it to 10x3x4 or 5x5x4, you can only change the right most dimension. |
Members of System.Array class
As we discuss earlier that all arrays are inherited from System.Array class which gives some common functionality to all arrays. In this section we will look at few very useful shared methods of System.Array class. The following list the properties and methods supported by all types of arrays. |
Public Properties
IsFixedSize |
Gets a value indicating whether the
Array has a fixed size. |
IsReadOnly |
Gets a value indicating whether the
Array is read-only. |
IsSynchronized |
Gets a value indicating whether access
to the Array is synchronized (thread-safe). |
Length |
Gets a 32-bit integer that represents
the total number of elements in all the dimensions of
the Array. |
LongLength |
Gets a 64-bit integer that represents
the total number of elements in all the dimensions of
the Array. |
Rank |
Gets the rank (number of dimensions) of
the Array. |
SyncRoot |
Gets an object that can be used to
synchronize access to the Array. |
Public Methods
BinarySearch |
Overloaded. Searches a one-dimensional
sorted Array for a value, using a binary search
algorithm. |
Clear |
Sets a range of elements in the Array
to zero, to false, or to a null reference (Nothing
in Visual Basic), depending on the element type. |
Clone |
Creates a shallow copy of the Array. |
Copy |
Overloaded. Copies a section of one
Array to another Array and performs type
casting and boxing as required. |
CopyTo |
Overloaded. Copies all the elements of
the current one-dimensional Array to the
specified one-dimensional Array. |
CreateInstance |
Overloaded. Initializes a new instance
of the Array class. |
Equals
(inherited from Object) |
Overloaded. Determines whether two
Object
|
GetEnumerator |
Returns an
IEnumerator for the Array
|
GetHashCode
(inherited from Object) |
Serves as a hash function for a
particular type, suitable for use in hashing algorithms
and data structures like a hash table. |
GetLength |
Gets a 32-bit integer that represents
the number of elements in the specified dimension of the
Array
|
GetLongLength |
Gets a 64-bit integer that represents
the number of elements in the specified dimension of the
Array
|
GetLowerBound |
Gets the lower bound of the specified
dimension in the Array
|
GetType
(inherited from Object) |
Gets the
Type
|
GetUpperBound |
Gets the upper bound of the specified
dimension in the Array
|
GetValue |
Overloaded. Gets the value of the
specified element in the current Array
|
IndexOf |
Overloaded. Returns the index of the
first occurrence of a value in a one-dimensional
Array or in a portion of the Array
|
Initialize |
Initializes every element of the
value-type Array
|
LastIndexOf |
Overloaded. Returns the index of the
last occurrence of a value in a one-dimensional Array
or in a portion of the Array
|
Reverse |
Overloaded. Reverses the order of the
elements in a one-dimensional Array or in a
portion of the Array
|
SetValue |
Overloaded. Sets the specified element
in the current Array
|
Sort |
Overloaded. Sorts the elements in
one-dimensional Array
|
ToString
(inherited from Object) |
Returns a
String that represents the current
Object. |
Finalize
(inherited from Object) |
Overridden. Allows an
Object to attempt to free resources and perform
other cleanup operations before the Object is
reclaimed by garbage collection.
|
MemberwiseClone
(inherited from Object) |
Creates a shallow copy of the current
Object
|
|
|
Sorting array (Array.Sort method)
Array.Sort method sorts an array. This is a very useful method and it has 8 different overloaded versions which can take different arguments to perform different operations. Let's look at few of them. |
Click here to copy the following block | Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click SortDemo() End Sub
Sub SortDemo()
Dim a1() As String = {"DDD", "ccc", "aaa", "BBB", "ddd", "AAA", "bbb", "CCC"} Dim myComparer = New myReverserClass
Console.WriteLine("Original array") PrintArray(a1)
Console.WriteLine("Sort 3 elements starting from index 0") Array.Sort(a1, 0, 3) PrintArray(a1)
Console.WriteLine("Default sort") Array.Sort(a1) PrintArray(a1)
Console.WriteLine("Case in-sensetive sort using custom compararor in reverse order") Array.Sort(a1, myComparer) PrintArray(a1)
End Sub
Sub PrintArray(ByVal arr As System.Array) Dim i As Integer
For i = 0 To arr.GetUpperBound(0) Console.WriteLine(" [{0}] : {1}", i, arr(i)) Next Console.WriteLine("=====================") Console.WriteLine() End Sub
Public Class myReverserClass Implements IComparer
Function Compare(ByVal x As Object, ByVal y As Object) As Integer _ Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x) End Function
End Class |
Original array
[0] : DDD
[1] : ccc
[2] : aaa
[3] : BBB
[4] : ddd
[5] : AAA
[6] : bbb
[7] : CCC
=====================
Sort 3 elements starting from index 0
[0] : aaa
[1] : ccc
[2] : DDD
[3] : BBB
[4] : ddd
[5] : AAA
[6] : bbb
[7] : CCC
=====================
Default sort
[0] : aaa
[1] : AAA
[2] : bbb
[3] : BBB
[4] : ccc
[5] : CCC
[6] : ddd
[7] : DDD
=====================
Case in-sensitive sort using custom comparer in reverse order
[0] : ddd
[1] : DDD
[2] : ccc
[3] : CCC
[4] : bbb
[5] : BBB
[6] : aaa
[7] : AAA
=====================
|
Locating an Element in an Array (Array.IndexOf method) |
Click here to copy the following block | Private Sub FindAnimal() Dim ZooAnimals(2) As String ZooAnimals(0) = "lion" ZooAnimals(1) = "turtle" ZooAnimals(2) = "ostrich" Dim turtle As Integer turtle = (Array.IndexOf(ZooAnimals,"turtle")) MsgBox("The turtle is element " & turtle) End Sub |
Fastest Search - Locating an Element in an Array (Array.BinarySearch method)
If your array is sorted and you want to search for some element then the most fasted method will be BinarySearch. This algorithm works only for sorted array so sometimes you will get correct result but in order to work 100% correct array must be sorted. |
Click here to copy the following block | Sub ArrDemo() Const MAX = 90000000 Dim arr(MAX) As Long Dim pos As Integer Dim i As Integer
For i = 0 To MAX arr(i) = i * 2 Next Console.WriteLine("Start BS:" & Date.Now) pos = (Array.BinarySearch(arr, 544564)) Console.WriteLine("End BS:" & Date.Now)
Console.WriteLine("Start IndexOf:" & Date.Now) pos = (Array.IndexOf(arr, 544564)) Console.WriteLine("End IndexOf:" & Date.Now)
End Sub |
Reversing the Contents of An Array (Array.Reverse method)
This example declares an array of String objects named Animals, populates it, and then reverses its contents. |
Click here to copy the following block | Private Sub ReverseSortAnimals() Dim Animals(2) As String Animals(0) = "lion" Animals(1) = "turtle" Animals(2) = "ostrich" Array.Reverse(Animals) End Sub |
Copying an array (Array.Copy, Array.CopyTo methods)
There are 2 main methods you can use to copy entire array to destination array. 1. Copy 2. CopyTo
Copy
Copies a section of one Array to another Array and performs type casting and boxing as required.
CopyTo
Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. |
Click here to copy the following block | Dim arr1() As Integer = {10, 20, 30, 40, 50} Dim arr2() As Integer = {60, 70, 80, 90, 100}
Array.Copy(arr1, 0, arr2, 0, 3)
Dim arr3(10) As Integer arr1.CopyTo(arr3, 2)
|
Using ArrayList for fast dynamic arrays
The last thing I want to discuss about is new set of classes which can be used to implement dynamic array functionality in VB.net. I know you can use ReDim to grow/shrink an Array but under the cover the ReDim Preserve statement creates a new array - and the elements of the old array get copied into the new one. As this happens under VB.NET implicitly, it won't be noticed except for performance loss. System.Collections.ArrayList is more easier and efficient way to handle dynamic arrays. |
Click here to copy the following block | Sub ArrayListDemo() Dim arrList As New System.Collections.ArrayList Dim arrRD() As Integer Dim i As Integer Dim dtStart As DateTime
dtStart = Now For i = 0 To 50000 ReDim Preserve arrRD(i) arrRD(i) = i * 5 Next Console.WriteLine("ReDim took " & Now.Subtract(dtStart).TotalMilliseconds & " miliseconds for 50000 elements")
dtStart = Now For i = 0 To 50000 arrList.Add(i * 5) Next Console.WriteLine("ArrayList took " & Now.Subtract(dtStart).TotalMilliseconds & " miliseconds for 50000 elements")
arrList(0) = 111 arrList(4) = 555
Console.WriteLine("First element :" & arrList(0)) Console.WriteLine("Fifth element :" & arrList(4)) End Sub |
ReDim took 10046.875 miliseconds for 50000 elements
ArrayList took 15.625 miliseconds for 50000 elements
First element :111
Fifth element :555
|
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|