03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

334 ❘ CHAPTER 14 Collection Classes<br />

(continued)<br />

Property/Method<br />

Count<br />

Dequeue<br />

Enqueue<br />

Peek<br />

ToArray<br />

TrimToSize<br />

Purpose<br />

Returns the number of items in the Queue.<br />

Returns and removes the item at the front of the Queue.<br />

Adds an item to the back of the Queue.<br />

Returns a reference to the item at the front of the Queue without<br />

removing it.<br />

Returns a one-dimensional array containing references to the objects<br />

in the Queue. The item at the front of the Queue is placed first in<br />

the array.<br />

Frees any empty space in the Queue.<br />

Like Stacks, Queues must resize themselves if they become full and that slows things down. Also like<br />

Stacks, Queues provide overloaded constructors that let you determine how big the Queue is initially.<br />

The first constructor takes no parameters and allocates a default initial capacity. If the Queue is full,<br />

it enlarges itself by a default growth factor.<br />

The second constructor takes as a parameter the Queue’s initial capacity. If you know that you will<br />

add 1,000 items to the Queue, you can save some time by initially allocating room for 1,000 items.<br />

With this constructor, the Queue also uses a default growth factor.<br />

The third constructor takes as a parameter an object that implements the ICollection interface. The<br />

constructor allocates enough room to hold the items in the ICollection and copies them into the<br />

Queue. This version also uses a default growth factor.<br />

The final version of the constructor takes as parameters an initial capacity and a growth factor<br />

between 1.0 and 10.0. A larger growth factor means the Queue resizes itself less often, but also<br />

means it may contain a lot of unused space.<br />

The following short example demonstrates a Queue.<br />

Queue queue = new Queue();<br />

queue.Enqueue("Apple");<br />

queue.Enqueue("Banana");<br />

queue.Enqueue("Cherry");<br />

Console.WriteLine(queue.Dequeue());<br />

Console.WriteLine(queue.Dequeue());<br />

Console.WriteLine(queue.Dequeue());<br />

This code creates a Queue and adds three strings to it. It then dequeues the three values, displaying<br />

the results in the Console window. The following text shows the results.<br />

Apple<br />

Banana<br />

Cherry<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!