C# Collections


To construct and manipulate a collection of objects, .Net framework has provided us with many classes. ArrayList, BitArray, HashTable, SortedList, Queue and Stack are some of them. They are all included in System.Collections namespace.

Download myQueue.cs

Download myStack.cs

In general, Arrays are not dynamic in nature and do not allow the user to remove an element easily. An ArrayList is like an expandable array of objects. Its Add, Insert, Remove RemoveAt methods make it relatively easy to insert and remove elements from the ArrayList. But we cannot refer to an entry in an ArrayList by a key. HastTable solves this problem but it does not allow its entries to be addressed using indexes. It also does not allow us to retrieve the entries in any particular order. SortedList represents a collection of associated keys & values. The values are sorted by key and are accessible by key and by Index.

The purpose of this paper is to demonstrate the use of stack and Queue classes, identify their key strengths and limitations. This paper first explains the stack/queue concept and then applies the concept to an example. The program is explained with the help of comment lines.

STACK

Stack class is generally referred to as LIFO (Last In First Out). The best example could be “a stack of plates in the fabrication company”. The last plate placed on the stack is the first one to be removed. Stack in implemented as circular buffer. The various methods of stack class are

Push
Inserts an object at the top of the Stack

Pop
Returns and permanently removes the object at the top of the Stack

Peek
Returns the object at the top of the Stack without removing it

Clear
Clears the stack by removing all objects from the Stack

Clone
Creates a shallow copy of the Stack

CopyTo
Copies the Stack to an existing one-dimensional Array

ToArray
Copies the Stack to a new array

Contains
Determines if an element is present in the Stack

Equals
Determines if two Object instances are equal

ToString
Returns a String that represents the current Object

GetEnumerator, GetHashCode and GetType are also some of the methods of stack class.
Count, IsReadOnly, IsSynchronized, SyncRoot are the properties of Stack class.

The initial capacity is the starting capacity of the new stack. Once current capacity is reached, the capacity is doubled. The default initial capacity is 10. Almost all the methods of Stack class, except Synchronized method are virtual and can be overridden by the derived class. Stack is not thread-safe, To guarantee thread safety of a stack, all operations must be done through the wrapper returned by the Synchronized method.

Example using Queue

The Code

// This example uses all the important methods of a stack class
using System;
using System.Collections;
public class myStack
{
public static void Main()
{ // Create and instantiate new Stack
Stack myStack = new Stack();
// Adding 4 objects to the stack
myStack.Push(“Vijay”);
myStack.Push(“Vikas”);
myStack.Push(“Emill”);
myStack.Push(“Rajiv”);
// Create and initialize one-dimensional Array
Array myArray=Array.CreateInstance(typeof(String),15);
// Add 5 elements to the array
myArray.SetValue(“student1″, 0);
myArray.SetValue(“student2″, 1);
myArray.SetValue(“student3″, 2);
myArray.SetValue(“student4″, 3);
myArray.SetValue(“student5″, 4);
// Count the number of objects in the stack
Console.Write(“Total number of objects in the stack : ” );
Console.Write(myStack.Count);
// Print all the objects in the stack
Console.Write(“\nThe objects are :”);
PrintValues(myStack);
Console.WriteLine();
Console.WriteLine(“\tObject no \t3\t2\t1\t0″);
// Remove an element from the stack (Last In First Out)
Console.WriteLine();
Console.WriteLine(“Pop removes&shows Last element of the stack first”);
Console.Write(“The element removed is : ” );
Console.Write(“\t{0}”, myStack.Pop());
// Show an element from the stack
Console.WriteLine(“\nPeek method just shows an element but does not
remove it from the stack”);
Console.Write(“The element shown is : ” );
Console.Write(“\t{0}”, myStack.Peek());
Console.WriteLine();
// Count and print the number of objects in the stack
Console.Write(“\nTotal remaining number of objects in the stack : ” );
Console.Write(myStack.Count);
Console.WriteLine();
Console.Write(“\nThe objects are :”);
PrintValues(myStack);
Console.WriteLine();
Console.WriteLine(“\tObject no \t2\t1\t0″);;
// Clear the Stack.
myStack.Clear();
Console.WriteLine();
Console.Write(“The stack is cleared. Now, total number of objects = “);
Console.Write(myStack.Count);
Console.WriteLine();
// Refill the stack with different values
myStack.Push(“Patil”);
myStack.Push(“Agarwal”);
myStack.Push(“Tsankov”);
myStack.Push(“Gomes”);
myStack.Push(“Smith”);
// Count and print the number of objects in the stack
Console.WriteLine();
Console.Write(“Total number of NEW objects in the stack : ” );
Console.Write(myStack.Count);
Console.WriteLine();
Console.Write(“\nThe objects are :”);
PrintValues(myStack);
Console.WriteLine();
Console.WriteLine(“\tObject no \t4\t3\t2\t1\t0″);
Console.WriteLine();
// Display the values of the target Array instance.
Console.WriteLine(“The target Array contains following elements BEFORE
copying):” );
PrintValues(myArray,’ ‘);
// Copy the entire source Stack to target Array, starting at index 3.
myStack.CopyTo( myArray, 3 );
Console.WriteLine();
Console.WriteLine(“The target Array contains following elements AFTER
copying):” );
PrintValues(myArray,’ ‘);
}

Continues…

Pages: 1 2

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!