19.4. Queue

As the name implies, a Queue encapsulates a standard FIFO abstract data type. Queues are useful for storing objects to be processed in the order that they are received. The three most commonly used methods of a Queue are Peek, Enqueue, and Dequeue. Like an ArrayList, the capacity of a Queue object changes automatically as more objects are inserted.

The program below demonstrates how Queue can be used. The output is interspersed with the code to show the outputs of the different sections.

 1: using System;
 2: using System.Collections;
 3:
 4: public class TestClass{
 5:   public static void Main(){
 6:
 7:     Queue q = new Queue();
 8:
 9:     // Using Enqueue
10:     q.Enqueue("A");
11:     q.Enqueue("B");
12:     q.Enqueue("C");
13:     q.Enqueue("D");
14:     q.Enqueue("E");
15:     q.Enqueue("F");
16:     PrintCollection(q);
17:

Output:

Queue elements: A,B,C,D,E,F,

The static PrintCollection method defined on line 35 below prints out the elements in the Queue object passed in.

18:     // Using Count
19:     Console.WriteLine("Count: " + q.Count);
20:

Output:

Count: 6

21:     // Using Dequeue
22:     string token = (string)q.Dequeue();
23:     Console.WriteLine("Dequeued:" + token);
24:     token = (string)q.Dequeue();
25:     Console.WriteLine("Dequeued:" + token);
26:     PrintCollection(q);
27:

Output:

Dequeued:A
Dequeued:B
Queue elements: C,D,E,F,

Notice that the string object A is 'first in' and hence, when dequeued, shall be 'first out'.

28:     // Using Peek
29:     token = (string)q.Peek();
30:     Console.WriteLine("Peeked:" + token);
31:     PrintCollection(q);
32:   }
33:

Output:

Peeked:C
Queue elements: C,D,E,F,

Unlike Dequeue, Peek does not remove any element from the Queue object. It simply returns the element at the front of the queue without dequeuing it from the Queue object.

34:   // Prints out all elements in the Queue
35:   public static void PrintCollection (Queue q){
36:     IEnumerator enumerator = q.GetEnumerator();
37:     Console.Write("Queue elements: ");
38:
39:     while (enumerator.MoveNext())
40:       Console.Write(enumerator.Current + ",");
41:
42:     Console.WriteLine();
43:   }
44: }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.62.168