站内搜索: 请输入搜索关键词
当前页面: 图书首页 > From Java To C# A Developers Guide

From Java To C# A Developers Guide

[ directory ] Previous Section Next Section

19.6 Stack

As the name implies, a Stack encapsulates a standard LIFO abstract data type. You use the Pop and Push methods of the Stack class to retrieve and insert elements respectively. Like Queue, Stack also has a Peek method which returns the element that is next to be popped out without actually popping it out.

Calling Pop() on an empty Stack will result in a System.InvalidOperationException exception. To prevent that from happening, you can check the Stack's Count public property before invoking Pop().

 1: using System;
 2: using System.Collections;
 3:
 4: public class TestClass{
 5:   public static void Main(){
 6:
 7:     Stack s = new Stack();
 8:
 9:     // Using Push
10:     s.Push("A");
11:     s.Push("B");
12:     s.Push("C");
13:     PrintCollection(s);
14:

Output:

Stack elements: C,B,A,

The static PrintCollection method defined on line 40 below prints out the elements in the Stack object passed in.

15:     // Using Count
16:     Console.WriteLine("Count: " + s.Count);
17:

Output:

Count: 3
18:     // Using Peek
19:     string token = (string)s.Peek();
20:     Console.WriteLine("Peeked:" + token);
21:     PrintCollection(s);
22:

Output:

Peeked:C
Stack elements: C,B,A,
23:     // Using Pop
24:     token = (string)s.Pop();
25:     Console.WriteLine("Popped:" + token);
26:     PrintCollection(s);
27:

Output:

Popped:C
Stack elements: B,A,

Notice that the last element pushed in (string C) is popped out first.

28:     token = (string)s.Pop();
29:     Console.WriteLine("Popped:" + token);
30:     PrintCollection(s);
31:

Output:

Popped:B
Stack elements: A,
32:     token = (string)s.Pop();
33:     Console.WriteLine("Popped:" + token);
34:     PrintCollection(s);
35:

Output:

Popped:A
Stack elements:
36:     token = (string)s.Pop(); // InvalidOperationException

Output (runtime exception):


Unhandled Exception: System.InvalidOperationException: Stack empty at System.Collections
graphics/ccc.gif.Stack.Pop() at TestClass.Main()

When attempting to Pop an empty Stack, an InvalidOperationException will be thrown.

37:   }
38:
39:   // Prints out all elements in the Queue
40:   public static void PrintCollection (Stack s){
41:     IEnumerator enumerator = s.GetEnumerator();
42:     Console.Write("Stack elements: ");
43:
44:     while (enumerator.MoveNext())
45:       Console.Write(enumerator.Current + ",");
46:
47:     Console.WriteLine();
48:   }
49: }

It is possible to Push onto a Stack a null instead of an object. nulls are often used as placeholders on the Stack to separate consecutive objects.

    [ directory ] Previous Section Next Section