DekGenius.com
[ Team LiB ] Previous Section Next Section

C.1 Usage

This section demonstrates how you can take advantage of container types. We don't illustrate all methods and properties, but we show the important characteristics of these types. All examples in this chapter are in C#; however, you can use these CLS types from any other CLS-compliant languages.

C.1.1 Array

Array, by definition, stores homogeneous information in a structure that allows for indexing, enumerating, and so on. It is very important in the daily programmer's life. In the following code listing, we demonstrate some of the syntax for using Array. In C#:

using System;
public class TestArray {

   public static void Main(  )  {

      string[] strArray = new string[7] { "Monday", "Tuesday", "Wednesday", 
"Thursday", "Friday", "Saturday", "Sunday" };
      for(int i=0; i<strArray.Length; i++) {
         Console.WriteLine(String.Format("item at {0} is {1}",
                                         i, strArray[i]));
      }

      int[] iArray;
      iArray = new int[7];

      for(int i=0; i<iArray.Length; i++) {
         iArray[i] = i;
      }
      for(int i=0; i<iArray.Length; i++) {
         Console.WriteLine(iArray[i]);
      }

   }
}

and in VB:

Imports System
Public Class TestArray

   Public Shared Sub Main(  )

      Dim i as Integer
      Dim strArray(  ) as String = { "Monday", "Tuesday", "Wednesday", 
"Thursday", "Friday", "Saturday", "Sunday" }

      For i = 0 To strArray.Length - 1
         Console.WriteLine(String.Format("item at {0} is {1}", _
                                         i, strArray(i)))
      Next

      Dim iArray(6) as Integer

      For i = 0 To iArray.Length - 1
         iArray(i) = i
      Next
      For i = 0 to iArray.Length - 1
         Console.WriteLine(iArray(i))
      Next

   End Sub
End Class

Notice the differences in the declaration of the array for the highlighted code. In VB, the number represents the upper bound of the array, not the size.

C.1.2 ArrayList

In the following code listing, we demonstrate some of the critical usages of the ArrayList class, such as adding data to the end of the list, inserting data anywhere in the list, iterating through the list, and sorting the list:

using System;
using System.Collections;
public class TestArrayList {

   public static void Main(  )  {

      ArrayList arrList = new ArrayList(  );
      arrList.Add("Monday");
      arrList.Add("Tuesday");
      arrList.Add("Wednesday");
      arrList.Add("Thursday");

      // We'll try to insert Friday afterward.
      // arrList.Add("Friday");

      arrList.Add("Saturday");
      arrList.Add("Sunday");

      int i = 0;
      IEnumerator arrIterator = arrList.GetEnumerator(  );
      Console.WriteLine("There are: {0} days in a week.", arrList.Count);
      while(arrIterator.MoveNext(  )) {
         Console.WriteLine("[{0}] {1}", i++, arrIterator.Current);
      }

      Console.WriteLine("Insert Friday");
      arrList.Insert(4, "Friday");

      i = 0;
      arrIterator = arrList.GetEnumerator(  );
      Console.WriteLine("There are: {0} days in a week.", arrList.Count);
      while(arrIterator.MoveNext(  )) {
         Console.WriteLine("[{0}] {1}", i++, arrIterator.Current);
      }

      arrList.Sort(  );

      i = 0;
      arrIterator = arrList.GetEnumerator(  );
      Console.WriteLine("Sorted as text");
      while(arrIterator.MoveNext(  )) {
         Console.WriteLine("[{0}] {1}", i++, arrIterator.Current);
      }

      Object oDay = "Friday";
      Console.WriteLine("Index for Friday using BinarySearch: {0}", 
                        arrList.BinarySearch(oDay));
      Console.WriteLine("Index for Sunday using BinarySearch: {0}", 
                        arrList.BinarySearch("Sunday"));
   }
}

C.1.3 BitArray

The sample code for BitArray is self-explanatory, as shown in the following code listing. We use the bit array to store and retrieve access rights in the following example. You can use the Set and Get methods as well as the [] operator:

using System;
using System.Collections;
public class TestBitArray  {

   enum Permissions {canRead, canWrite, canCreate, canDestroy};      

   public static void Main(  )  {
   
      BitArray bitArr = new BitArray(4);
      bitArr.Set((int)Permissions.canRead, true);
      bitArr[(int)Permissions.canWrite] = false;
      bitArr[(int)Permissions.canCreate] = true;
      bitArr[(int)Permissions.canDestroy] = false;

      Console.WriteLine("bitArr count: {0}\tlength: {1}", 
                        bitArr.Count, 
                        bitArr.Length);

      Console.WriteLine("Permissions:");
      Console.WriteLine("Read: {0}", 
                        bitArr[(int)Permissions.canRead]);
      Console.WriteLine("Write: {0}", 
                        bitArr[(int)Permissions.canWrite]);
      Console.WriteLine("Create: {0}", 
                         bitArr[(int)Permissions.canCreate]);
      Console.WriteLine("Destroy: {0}", 
                         bitArr[(int)Permissions.canDestroy]);
   }
}

C.1.4 HashTable

The HashTable data type is similar to the dictionary object, which is basically an associated array. Each element stored in the table is associated with a key. Because HashTable implements the IDictionaryEnumerator, we can obtain the enumerator to help us iterate through the data collection. As you can see from the sample code, we can also loop through the data using the keys or values collection:

using System;
using System.Collections;
public class TestHashtable  {

   public static void Main(  )  {

      Hashtable hashTbl = new Hashtable(  );
      hashTbl.Add("Param1", "UserName");
      hashTbl.Add("Param2", "Password");

      IDictionaryEnumerator hashEnumerator = hashTbl.GetEnumerator(  );
      Console.WriteLine(  );
      Console.WriteLine("Loop through with enumerator:");
      while (hashEnumerator.MoveNext(  )) {
         Console.WriteLine("Key: {0}\tValue: {1}", 
                           hashEnumerator.Key, 
                           hashEnumerator.Value);
      }

      Console.WriteLine(  );
      Console.WriteLine("Loop through Keys:");
      foreach(string key in hashTbl.Keys) {
         Console.WriteLine(key); 
      }

      Console.WriteLine(  );
      Console.WriteLine("Loop through Values:");
      foreach(string val in hashTbl.Values) {
         Console.WriteLine(val); 
      }

      Console.WriteLine(  );
      Console.WriteLine("Loop through Keys:");
      foreach(string key in hashTbl.Keys) {
         Console.WriteLine("Key: {0}\tValue: {1}", key, hashTbl[key]);
      }
   }
}

C.1.5 Queue

To demonstrate the use of a queue Abstract Data Type (ADT), we created a fictitious order-processing code listing. Each enqueued item represents a line item in a typical order. We will then dequeue each line item and perform the total calculation:

using System;
using System.Collections;

public class TestQueue  {

   public static void Main(  )  {
      string sLineItem1, sLineItem2;
      Queue myQueue = new Queue(  );

      sLineItem1 = "123\tItem 123\t4\t3.39";
      sLineItem2 = "ABC\tItem ABC\t1\t9.49";
      myQueue.Enqueue(sLineItem1);
      myQueue.Enqueue(sLineItem2);

      Console.WriteLine("\nProcessing Order:\n");
      String sLineItem = "";
      String [] lineItemArr;
      Decimal total = 0;
      while(myQueue.Count > 0) {
         sLineItem = (String)myQueue.Dequeue(  ); 
         Console.WriteLine( "\t{0}", sLineItem);
         lineItemArr = sLineItem.Split(new Char[] {'\t'});
         total += Convert.ToInt16(lineItemArr[2]) *
                 Convert.ToDecimal(lineItemArr[3]);
      }
      Console.WriteLine("\nOrder Total: {0}\n", total);
   }
}

C.1.6 SortedList

The following code demonstrates the sorted list ADT. A sorted list is similar to a hash table or a dictionary type. Each item of data is associated with the key with which the list is sorted. Notice that the strings are added to the list in no particular order. However, when we iterate through the list, all strings are sorted by their associated keys:

using System;
using System.Collections;
public class TestSortedList  {

   public static void Main(  )  {

      SortedList mySortedList = new SortedList(  );
      mySortedList.Add("AA", "Hello");
      mySortedList.Add("AC", "!");
      mySortedList.Add("AB", "World");

      Console.WriteLine("\nLoop through manually:\n");
      for(int i=0; i< mySortedList.Count; i++) {
         Console.WriteLine("Key: {0}\tValue: {1}", 
                           mySortedList.GetKey(i), 
                           mySortedList.GetByIndex(i));
      }

      IDictionaryEnumerator myIterator = mySortedList.GetEnumerator(  );
      Console.WriteLine("\nLoop through with enumerator:\n");
      while (myIterator.MoveNext(  )) {
         Console.WriteLine("Key: {0}\tValue: {1}", 
                           myIterator.Key, 
                           myIterator.Value);
      }
   }
}

C.1.7 Stack

The following code demonstrates the first-in, last-out characteristics of the stack abstract data type. The output from the pop operation initially shows the fourth item, the third item, and so on:

using System;
using System.Collections;
public class TestStack{

   public static void Main(  )  {

      Stack myStack = new Stack(  );
      myStack.Push("Item 1");
      myStack.Push("Item 2");
      myStack.Push("Item 3");
      myStack.Push("Item 4");

      while(myStack.Count > 0) {
         Console.WriteLine(myStack.Pop(  ));
      }
   }
}
    [ Team LiB ] Previous Section Next Section