#845 – Using the Generic Queue Class

A queue is a data structure that allows adding elements at one end of the queue, through Enqueue operations, and removing elements from the other end, through Dequeue operations.

The .NET Framework includes a Queue<T> type, defined in System.Collections.Generic, that implements a queue data type.

When you declare a queue, you indicate the type of objects that the queue will contain.

            Queue<Person> peopleInLine = new Queue<Person>();

You can now add instances of Person objects to the (back of) the queue using the Enqueue method.

            // Ernest - 1st guy in line
            peopleInLine.Enqueue(new Person("Ernest", "Hemingway"));

            // Scott in line behind Ernest
            peopleInLine.Enqueue(new Person("F. Scott", "Fitzgerald"));

845-001
You can remove the object from the front of the queue using the Dequeue method.

            // Remove guy from front of line -- Ernest
            Person next = peopleInLine.Dequeue();

845-002

#844 – The Queue Data Type

A queue is a data type used to store a collection of items and which has the following properties:

  • Elements can be added to the queue
  • Elements can be removed from the queue, but only in the order in which they were added

Adding an item is known as a Enqueue operation.  Removing an item is known as a Dequeue  operation.

You can think of a queue data type as being like people standing in a line.  You can enter the line only at the back (Enqueue) and you can leave the line, but only from the front (Dequeue).

A queue is also known as a FIFO (First-In, First-Out) structure.

844-001