Queue: First-In, First-Out List.
here’s how you use Queue. To put an object in the queue, call Enqueue(). To remove and return the object at the front of the queue, call Dequeue(). An InvalidOperationException is thrown if you call Deueue() when the invoking queue is empty. You can use Peek() to return, but not remove, the next object.
Here is an example that demonstrates Queue:
//Demonstrate the Queue class.
using System; using System.Collections;
class QueueDemo { static void ShowEnqueue(Queue queue, int number) { queue.Enqueue(number); Console.WriteLine("Enqueue(" + number + ")"); Console.Write("queue: "); foreach(int i in queue) Console.Write(i + " "); Console.WriteLine(); } static void ShowDequeue(Queue queue) { Console.Write("Dequeue -> "); int number = (int) queue.Dequeue(); Console.WriteLine(number); Console.Write("queue: "); foreach(int i in queue) Console.Write(i + " "); Console.WriteLine(); } public static void Main() { Queue queue = new Queue();
foreach(int i in queue) Console.Write(i + " "); Console.WriteLine();
ShowEnqueue(queue,1); ShowEnqueue(queue,5); ShowEnqueue(queue,90); ShowDequeue(queue); ShowDequeue(queue); ShowDequeue(queue);
try { ShowDequeue(queue); } catch(InvalidOperationException) { Console.WriteLine("Queue empty."); Console.Read(); } } }
The output is shown here:
Enqueue(1) queue: 1 Enqueue(5) queue: 1 5 Enqueue(90) queue: 1 5 90 Dequeue -> 1 queue: 5 90 Dequeue -> 5 queue: 90 Dequeue -> 90 queue: Dequeue -> Queue empty.
|
| Author: Emmanuel Mathew 14 Jun 2004 | Member Level: Silver Points : 0 |
Hi,
When we try to dequeue from a queue, InvalidOperationException occurs. So how did you know that the Exception is this specific one? Or first did you try out with the common exception and you gt the name from exceptionObject.message() and then put specific catch for the particular error?
I hope you can understand my question...
Thanks in Advance
Bye
|
| Author: Emmanuel Mathew 14 Jun 2004 | Member Level: Silver Points : 0 |
Sorry, In the above question, I meant dequeue from an empty Queue. Also how I can know that a Queue is empty?
Is there any other method rather than waiting for the error and catching it? And also I have heard that If the program traverses thru a lot of Exceptions, the efficiency of code decreases. Is it true?
I hope I am not annoying you...
Thanks in Advance.... Bye
|
| Author: Slymenstra Hymen 17 Jun 2004 | Member Level: Bronze Points : 0 |
static void ShowDequeue(Queue queue) { Console.Write("Dequeue -> "); int number; if ( queue.Count != 0 ) { number = (int) queue.Dequeue(); Console.WriteLine(number); } else { Console.WriteLine("queue is empty"); } Console.Write("queue: "); foreach(int i in queue) Console.Write(i + " "); Console.WriteLine(); }
|