This method returns the object at the beginning of the Queue without removing it. This method is similar to the Dequeue method, but Peek does not modify the Queue and is an O(1) operation. This method comes under System.Collections namespace.
Syntax:
public virtual object Peek ();
Return Value: The object at the beginning of the Queue.
Exception: This method will give InvalidOperationException if the Queue is empty.
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Queue myQueue = new Queue();
myQueue.Enqueue( "1st Element" );
myQueue.Enqueue( "2nd Element" );
myQueue.Enqueue( "3rd Element" );
myQueue.Enqueue( "4th Element" );
myQueue.Enqueue( "5th Element" );
myQueue.Enqueue( "6th Element" );
Console.Write( "Total number of elements in the Queue are : " );
Console.WriteLine(myQueue.Count);
Console.WriteLine( "Element at the beginning is : "
+ myQueue.Peek());
Console.WriteLine( "Element at the beginning is : "
+ myQueue.Peek());
Console.Write( "Total number of elements in the Queue are : " );
Console.WriteLine(myQueue.Count);
}
}
|
Output:
Total number of elements in the Queue are : 6
Element at the beginning is : 1st Element
Element at the beginning is : 1st Element
Total number of elements in the Queue are : 6
Example 2:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Queue myQueue = new Queue();
Console.WriteLine( "Element at the beginning is : "
+ myQueue.Peek());
}
}
|
Runtime Error:
Unhandled Exception:
System.InvalidOperationException: Queue empty.
Reference:
Last Updated :
04 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...