Queue Class

Definition

Represents a first-in, first-out collection of objects.

public ref class Queue : System::Collections::ICollection
public ref class Queue : ICloneable, System::Collections::ICollection
public class Queue : System.Collections.ICollection
public class Queue : ICloneable, System.Collections.ICollection
[System.Serializable]
public class Queue : ICloneable, System.Collections.ICollection
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class Queue : ICloneable, System.Collections.ICollection
type Queue = class
    interface ICollection
    interface IEnumerable
type Queue = class
    interface ICollection
    interface IEnumerable
    interface ICloneable
[<System.Serializable>]
type Queue = class
    interface ICollection
    interface IEnumerable
    interface ICloneable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Queue = class
    interface ICollection
    interface IEnumerable
    interface ICloneable
Public Class Queue
Implements ICollection
Public Class Queue
Implements ICloneable, ICollection
Inheritance
Queue
Attributes
Implements

Examples

The following example shows how to create and add values to a Queue and how to print out its values.

using namespace System;
using namespace System::Collections;
void PrintValues( IEnumerable^ myCollection );
int main()
{
   
   // Creates and initializes a new Queue.
   Queue^ myQ = gcnew Queue;
   myQ->Enqueue( "Hello" );
   myQ->Enqueue( "World" );
   myQ->Enqueue( "!" );
   
   // Displays the properties and values of the Queue.
   Console::WriteLine( "myQ" );
   Console::WriteLine( "\tCount:    {0}", myQ->Count );
   Console::Write( "\tValues:" );
   PrintValues( myQ );
}

void PrintValues( IEnumerable^ myCollection )
{
   IEnumerator^ myEnum = myCollection->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "    {0}", obj );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 myQ
     Count:    3
     Values:    Hello    World    !
*/
 using System;
 using System.Collections;
 public class SamplesQueue  {

    public static void Main()  {

       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue("Hello");
       myQ.Enqueue("World");
       myQ.Enqueue("!");

       // Displays the properties and values of the Queue.
       Console.WriteLine( "myQ" );
       Console.WriteLine( "\tCount:    {0}", myQ.Count );
       Console.Write( "\tValues:" );
       PrintValues( myQ );
    }

    public static void PrintValues( IEnumerable myCollection )  {
       foreach ( Object obj in myCollection )
          Console.Write( "    {0}", obj );
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.

 myQ
     Count:    3
     Values:    Hello    World    !
*/
Imports System.Collections

Public Class SamplesQueue

    Public Shared Sub Main()

        ' Creates and initializes a new Queue.
        Dim myQ As New Queue()
        myQ.Enqueue("Hello")
        myQ.Enqueue("World")
        myQ.Enqueue("!")

        ' Displays the properties and values of the Queue.
        Console.WriteLine("myQ")
        Console.WriteLine("    Count:    {0}", myQ.Count)
        Console.Write("    Values:")
        PrintValues(myQ)

    End Sub

    Public Shared Sub PrintValues(myCollection As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myCollection
            Console.Write("    {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub

End Class


' This code produces the following output.
' 
' myQ
'     Count:    3
'     Values:    Hello    World    !

Remarks

This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other.

Important

We don't recommend that you use the Queue class for new development. Instead, we recommend that you use the generic Queue<T> class. For more information, see Non-generic collections shouldn't be used on GitHub.

Queues and stacks are useful when you need temporary storage for information; that is, when you might want to discard an element after retrieving its value. Use Queue if you need to access the information in the same order that it is stored in the collection. Use Stack if you need to access the information in reverse order. Use ConcurrentQueue<T> or ConcurrentStack<T> if you need to access the collection from multiple threads concurrently.

Three main operations can be performed on a Queue and its elements:

  • Enqueue adds an element to the end of the Queue.

  • Dequeue removes the oldest element from the start of the Queue.

  • Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.

The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize.

The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. The default growth factor is 2.0. The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required.

Queue accepts null as a valid value and allows duplicate elements.

For the generic version of this collection, see System.Collections.Generic.Queue<T>

Constructors

Queue()

Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default growth factor.

Queue(ICollection)

Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor.

Queue(Int32)

Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor.

Queue(Int32, Single)

Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor.

Properties

Count

Gets the number of elements contained in the Queue.

IsSynchronized

Gets a value indicating whether access to the Queue is synchronized (thread safe).

SyncRoot

Gets an object that can be used to synchronize access to the Queue.

Methods

Clear()

Removes all objects from the Queue.

Clone()

Creates a shallow copy of the Queue.

Contains(Object)

Determines whether an element is in the Queue.

CopyTo(Array, Int32)

Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.

Dequeue()

Removes and returns the object at the beginning of the Queue.

Enqueue(Object)

Adds an object to the end of the Queue.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

Returns an enumerator that iterates through the Queue.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Peek()

Returns the object at the beginning of the Queue without removing it.

Synchronized(Queue)

Returns a new Queue that wraps the original queue, and is thread safe.

ToArray()

Copies the Queue elements to a new array.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
TrimToSize()

Sets the capacity to the actual number of elements in the Queue.

Extension Methods

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to

Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized(Queue) method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

See also