In my last post you can find explanation of Stack Collection. Concept of both collections is similar.
Queue is a FIFO(first-in, first out) collection of objects. It’s generic type that is part of System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class:Enqueue(Object),Dequeue(),Peek(). First lets explain the FIFO concept.
Queue line can be a good, real world example of FIFO concept. Person who will stand in line first will be served first. Using this concept we can enqueue the items into a queue and get it in the same order. Let’s move on to class syntax.
Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.
Queue<int> queue = new Queue<int>();
Let’s look at the methods
Enqueue(Object)
class Program { static void Main() { Queue<int> queue = new Queue<int>(); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); queue.Enqueue(4); } }
We crate new queue and by using Enqueue() method we add new items to the collection. Simple as that
Dequeue()
Removes the object at the beginning of your Queue. The algorithmic complexity of this is O(1). It doesn’t loop over elements.
queue.Dequeue();
this method doesn’t take any parameters
Peek()
This method works the same way as in stack. It returns the value without removing it. In this case first value in queue.
queue.Peek();
This is not the most popular type of collections, but it can be useful for creating things like for example, player turn system in strategy game. In next post I’ll cover another type of collection, bitArray. Stay Awesome!