13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

100 CHAPTER 3 Parameterized typ<strong>in</strong>g with genericsJust as with List, there is no way of obta<strong>in</strong><strong>in</strong>g a synchronized Dictionary,nor does it implement ICloneable. The dictionary equivalent of Synchronized-Collection is SynchronizedKeyedCollection (which <strong>in</strong> fact derives fromSynchronizedCollection).With the lack of additional functionality, another example of Dictionarywould be relatively po<strong>in</strong>tless. Let’s move on to two types that are closely related toeach other: Queue and Stack.3.5.3 Queue and StackThe generic queue and stack classes are essentially the same as their nongeneric counterparts.The same features are “miss<strong>in</strong>g” from the generic versions as with the othercollections—lack of clon<strong>in</strong>g, and no way of creat<strong>in</strong>g a synchronized version. Asbefore, the two types are closely related—both act as lists that don’t allow randomaccess, <strong>in</strong>stead only allow<strong>in</strong>g elements to be removed <strong>in</strong> a certa<strong>in</strong> order. Queues act <strong>in</strong>a first <strong>in</strong>, first out (FIFO) fashion, while stacks have last <strong>in</strong>, first out (LIFO) semantics.Both have Peek methods that return the next element that would be removed butwithout actually remov<strong>in</strong>g it. This behavior is demonstrated <strong>in</strong> list<strong>in</strong>g 3.14.List<strong>in</strong>g 3.14Demonstration of Queue and StackQueue queue = new Queue();Stack stack = new Stack();for (<strong>in</strong>t i=0; i < 10; i++){queue.Enqueue(i);stack.Push(i);}for (<strong>in</strong>t i=0; i < 10; i++){Console.WriteL<strong>in</strong>e ("Stack:{0} Queue:{1}",stack.Pop(), queue.Dequeue());}The output of list<strong>in</strong>g 3.14 is as follows:Stack:9 Queue:0Stack:8 Queue:1Stack:7 Queue:2Stack:6 Queue:3Stack:5 Queue:4Stack:4 Queue:5Stack:3 Queue:6Stack:2 Queue:7Stack:1 Queue:8Stack:0 Queue:9You can enumerate Stack and Queue <strong>in</strong> the same way as with a list, but <strong>in</strong> myexperience this is used relatively rarely. Most of the uses I’ve seen have <strong>in</strong>volved athread-safe wrapper be<strong>in</strong>g put around either class, enabl<strong>in</strong>g a producer/consumerLicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!