Page 1 of 1

Arrays and Collections Overview Rate Topic: -----

#1 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3478
  • View blog
  • Posts: 11,818
  • Joined: 12-December 12

Posted 01 November 2013 - 02:48 PM

The following provides an overview, or summary, of these subjects. For further information the two main Microsoft resources are:

Arrays in Visual Basic :MSDN
Collections (C# and Visual Basic) :MSDN

These linked pages are very good and I've borrowed a few code-snippets from them.

Look through the other tutorials here @DIC as well though. In particular, there are tutorials that make use of specific collection-types.

Arrays

Arrays are groups of similar values (or object-references) that are stored in indexed order. Arrays start from - are indexed from - zero. That is, the first element of an array is arrayName(0).

Dim some(100) As Integer    'an upper bound of 100
'this array contains 101 elements, identified as some(0) through to some(100)

Dim more(100, 10) As Integer    'multi-dimensional array
Dim again(0 To 100) As Integer  'can only really be 0 anyway, so don't use this.

Dim a1(10) As Integer
ReDim a1(20)            'now permitted
Dim a2() As Integer     'a dynamic array


Formerly, to resize an array required that the array be declared without dimensions being specified - myArray() - which creates a dynamic array. You can now resize any array using the ReDim statement (see below), or ReDim Preserve if you wish to keep the values already stored in the array.

ReDim a2(20)
Dim a3(,,) As Integer
ReDim a3(10, 20, 30)


ReDim and Preserve are keywords carried over from VB6. The preferred .NET method is:

Dim intArray() As Integer
intArray = New Integer(10) {}


Iterating Arrays

The LBound(array_name) and UBound(array_name) functions determine the upper and lower bounds for dynamic, or fixed, arrays. However, LBound is of limited use as it will always return 0, and the GetUpperBound method is preferred to UBound as it enables you to specify which dimension to examine.

The following examples are from Arrays in Visual Basic :MSDN, using both For..Next and For..Each to loop through (iterate) arrays.

Spoiler





If you don't know how many elements the array might have then use a List type instead. With a List you can easily Add new elements and still reference elements with an index.

Dim strNames As New List(Of String)
strNames.Add("Ray Barone")
strNames.Add("Marie Barone")
Console.WriteLine(strNames(0))





Array Initializers

To declare and initialize an array in one statement, you must omit the array's bounds:

Dim fibonacci() As Integer = {1, 1, 2, 3, 5, 8, 13, 21}
Dim strings() = { "A", "B", "C" }   'with Option Infer On
Dim objects() = { "A", 12, 1.23 }
Dim int_values(,) As Integer = { { 1, 2, 3 }, { 4, 5, 6 } }



Jagged Arrays

A jagged array can be more efficient with large arrays where the number of columns varies a great deal.

Dim jaggedArray(10)() As Integer
jaggedArray(0) = New Integer(4) {}
jaggedArray(0)(0) = 54      'this referencing differs to that for a
'multi-dimensional array, which uses (0, 0)

Dim jags As Integer()()
jags = New Integer(10)() {}

Dim jags2(5)() As Integer
jags2 = New Integer()() { New Integer() {1, 2, 3}, New Integer() { 4, 5, 6, 7 } }


This first statement creates a two-dimensional array with 11 rows, but an unknown number of columns for each row. The second statement creates a new array with five elements, which is stored as the first element of the jagged array. Each row is assigned a new array in the same manner. Note: The distinction between rows and columns when discussing arrays is somewhat arbitrary (I notice that the linked MSDN page avoids this terminology).

Looping through a jagged array is cumbersome: loop through the rows, examining the upper-bound for the other dimension(s) within each loop. If you need to do this frequently then the efficiency gained through the use of a jagged array may be lost.

Spoiler

Collections

Collections (C# and Visual Basic) :MSDN

The word collection simply means a group of objects that should be kept together. Unfortunately, Visual Basic also uses this term for its specific Collection Class, which can lead to some confusion.

The simplest type of collection is an array. An array stores data values or references to objects in a simple block of memory with one entry directly following another. The Array Class provides some special methods for manipulating arrays, such as reversing, sorting, or searching an array.

The Collection Class provides a few specific features for working with its group of objects. It enables you to add an item to the Collection, optionally specifying a key for the item. You can then search for the item or remove the item using its key or its index in the Collection.

One of the most useful features of the Collection class is that it supports enumerators and For Each loops. This lets you easily loop over the objects in a Collection without worrying about the number of objects it contains.

Other classes derived from the Collection class provide additional features. For example, the Hashtable class can store a large number of objects with associated keys very efficiently. Dictionary is essentially a strongly-typed generic Hashtable so, although the Hashtable uses the Object data type for its key/value pairs, the Dictionary uses more specific data types that you specify, such as Strings or Employees. The Queue class makes it easy to work with objects on a first in, first out (FIFO) basis, whereas the Stack class helps you work with objects in a last in, first out order (LIFO).

The Array Class

Normal/standard arrays are discussed above. Visual Basic also provides an Array Class. This provides additional features, such as sorting and copying methods, but can be significantly slower than variable arrays – particularly with large datasets.

Public Sub UseArrayClass()
    Dim squares As Array = Array.CreateInstance(GetType(Integer), 11)
    For i As Integer = 0 To 10
        squares.SetValue(i * i, i)
    Next i
    Dim strArr As String = ""
    For i As Integer = 0 To 10
        strArr &= squares.GetValue(i).ToString & vbCrLf
    Next i
    Console.WriteLine(strArr)
End Sub


With Option Strict Off, you would not have to use the Get and SetValue methods; you could use, for example, squares(i) = i * i. However, it is recommended that Option Strict remain On. Normal arrays always have lower bounds of zero. The Array classes' CreateInstance method can enable Array objects to have different lower bounds.

Array objects cannot be re-sized using the ReDim statement. However, it is easy to copy one Array objects' elements to another, using the CopyTo method:
old_array.CopyTo(new_array, 0)
'0 is the index in the destination array to start placing values


The Copy method allows you to specify the index in the source array to start from, the index in the destination array, and the number of items to copy.

Other Array Class methods: IndexOf, LastIndexOf, Reverse, Sort, BinarySearch.

Collection Classes

The Collection Class can do little more than store items. Other Collection classes provide many more features.

The ArrayList Class is a resizeable array of objects. You can add and remove items from any position in the list and it resizes accordingly. This class is not type-safe and List(Of T) is preferred.

Some ArrayList methods: Add, AddRange, Clear, Remove, RemoveAt, RemoveRange.

A StringCollection is similar to an ArrayList, except that it can hold only strings. This enables type and error checking and should be used when working with strings; that is, unless you need other features – such as the fast lookups provided by a Hashtable.

    Dim sLoves As New StringCollection
    sLoves.Add("Raymond")
    sLoves.Add("Debra")
    sLoves.AddRange({"Frank", "Marie", "Robert"})
    sLoves.Remove("Debra")

    For Each sCast In sLoves
        Console.Write(sCast & ", ")
    Next


Other collection classes are:

  • BitArray Manages an array of Booleans that are stored as bit values.
  • HashTable Implements a collection of values organized by key. Sorting is done based on a hash of the key.
  • Queue Implements a first in, first out collection.
  • SortedList Implements a collection of values with associated keys. The values are sorted by key and are accessible by key or index.
  • Stack Implements a last in, first out collection.


Strongly Typed Collections

A strongly typed collection is a collection class designed to work with a particular data type. StringCollection is an example of a strongly typed collection. You can define your own collection classes that are strongly typed.

To build a strongly typed collection from scratch, create a new class that inherits from System.Collections.CollectionBase. Inheriting from this class automatically gives your class an ArrayList object named List. It also gives your class some inherited routines that do not depend on the type of object you want the collection to hold. For example, the RemoveAt method removes the object at a specific index in the list.

Your class can implement other methods for adding and retrieving items in the collection. For example, it can implement the Add, Remove and Item methods. Fortunately, you don't need to build these methods from scratch. You can simply delegate them to the inherited List object. For example, the Add method can simply call List.Add:

Class Employee
    'not yet implemented
End Class

Public Class EmployeeCollection
    Inherits System.Collections.CollectionBase

    Public Sub Add(ByVal value As Employee)
        List.Add(value)
    End Sub
End Class


The EmployeeCollection class's Add method takes a parameter of a particular type (Employee), whereas the List object's Add method takes a generic Object as a parameter. This insistence on the Employee type is what makes this collection strongly typed.

The following table lists the standard methods provided by a strongly typed collection class. The third column indicates whether the CollectionBase parent class automatically provides the method, or whether you must delegate the method to the List object.

Posted Image

Generics provide another method for building strongly typed collections. For instance, List(Of T) is a generic type in that it is a template that defines a complete type or class:

Dim data As New List(Of Integer)


Deriving from the ReadOnlyCollectionBase Class, you can build a strongly typed collection class that can be examined but not modified.

The NameValueCollection Class is a collection that can hold more than one string value for a particular key (name), which is also a string. For example, an employee-id could be the key, and first-name, last-name, job title, could be the values. This could be useful if you don't know ahead of time how many strings will be associated with each key. With this collection it is easy to Remove a name (and associated values), but tricky to remove a value for a particular key; for example, to remove someone's job title. Note: This collection-class is quite specialised and shouldn't be your first choice. Employee details would be better stored in their own Class.

Dictionaries

A dictionary is a collection that associates keys with values. You look up a key, and the dictionary provides you with the corresponding value. This differs from a NameValueCollection because the keys and values needn't be strings, and a dictionary associates each key with a single value.

ListDictionary – stores its data in a linked list. This would be slow for a large list.

Hashtable – similar to a ListDictionary, but provides extremely fast access to its data using their keys. It works by mapping an object's key into a bucket by calculating the key's hash value.

HybridDictionary – A cross between a ListDictionary and a Hashtable. The compiler switches between the two classes.

You can make strongly typed dictionaries in a similar way to strongly typed collections, by inheriting from the DictionaryBase Class. Or you could inherit from, for example, the ListDictionary Class, if you know that you want the data to be internally stored as a ListDictionary rather than a hash table.

StringDictionary – uses a hash table to manage keys and values that are all strings, so is strongly typed.
    Dim sFruits As New StringDictionary
    With sFruits
        .Add("a", "Apple")
        .Add("b", "Banana")
        .Add("c", "Carrot")
        .Add("d", "Damson")
        .Remove("c")
    End With
    Console.WriteLine(String.Format("What is a {0}?", sFruits("d")))


SortedList – acts as a Hashtable/Array hybrid. When accessing a value by key, it behaves as a hash table. When accessing a value by index, it acts as an array. Only use this if you need its special properties.

CollectionsUtil – Provides methods that create case-insensitive Hashtable and SortedList objects.

Stacks and Queues

The Stack and Queue classes provide specialized data structures that add and remove items in a particular order.

A Stack returns items in last-in, first-out (LIFO) order, so is sometimes called a LIFO list. The Push method adds an item to the top of the stack, Pop removes the top item from the stack. Think of a stack of plates!

Stack(Of T) Class

MSDN said:

Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type.


I've also borrowed part of the example from that page:
Spoiler

A Queue returns items in first-in, first-out (FIFO) order. Enqueue adds, Dequeue removes from the queue. Think of the queue at your local bank!

Queue(Of T) Class

Collection Initializers

Collections that have an Add method can be initialized using the From keyword:

Spoiler


Generics - Brief Introduction

Generics in the .NET Framework :MSDN

Generics means you can use a generic type parameter T to write a class TheList(Of T) and that class can be used as TheList(Of Integer), TheList(Of Boolean) or even TheList(Of MyClass) and not have to worry about runtime conversion or illegal conversion/cast errors.

Public Class YourClass(Of type)
    'The class definition uses 'type' wherever you would
    'normally refer to an explicit data type, structure or class-name.
    'It is, however, an accepted convention to use the letter T.
End Class

Dim AnInstance As New YourClass(Of Integer) 'or String, etc..


(C++ has a similar feature called Templates, and this word is useful as you are effectively creating a template for your classes.)

The major advantages of Generics are:

  • Type safe: Using Generics forces type compliance at compile-time not run-time. This greatly reduces, if not eliminates, unhandled run-time exceptions due to data type conflicts.
  • Performance: Since the data type is determined at compile-time, there is no type-casting at run-time.
  • Re-usability: A class written with Generics is re-usable: there is no need to duplicate the class for different data types.


Generic Types

Similar to List(Of T) is the Dictionary(Of K, T) generic, which requires that you define the types of both the key data and the values to be stored. When you declare a variable as Dictionary(Of K, T), the new Dictionary type that is created only accepts keys of the first type and values of the other.

Spoiler




Concluding

I hope that you have found this tutorial helpful and welcome your comments or suggestions.

This post has been edited by andrewsw: 04 November 2013 - 06:20 AM


Is This A Good Question/Topic? 2
  • +

Page 1 of 1