Stack Class


Stack Class

Namespace

System.Collections (standard version)

System.Collections.Generic (generic version)

Creatable

Yes

Description

The Stack object implements a "last in, first out" (LIFO) data structure. Items are added to the top of the stack, and new items are placed "on top" of the previously added items. Only the current topmost item can be removed. A real-life parallel would be a stack of books or a stack of pancakes.

The stack includes features for adding items (Push), removing items (Pop), and counting the items in the stack (Count), among other features. Objects of any type may be added to the stack.

The following table lists some of the more useful and interesting members of the Stack class. Those marked with an asterisk (*) have separate entries in this chapter.

Member

Description

Clear Method

Removes all items from the stack

Clone Method

Makes a distinct copy of the stack and its members

Contains Method *

Indicates whether a specific object is on the stack

CopyTo Method *

Copies stack elements to an existing array

Count Property

Indicates the number of items currently on the stack

IsReadOnly Property

Indicates whether the stack is read-only or not

Peek Method *

Returns the top stack item without removing it

Pop Method *

Removes and returns the top item on the stack

Push Method *

Adds a new item to the top of the stack

ToArray Method*

Copies the stack to a new array


Example

This sample code shows the basic use of the stack.

     ' ----- Add some basic items to a stack.     Dim nameStack As New Stack     nameStack.Push("Chopin")     nameStack.Push("Mozart")     nameStack.Push("Beethoven")     ' ----- Examine and return the items.     MsgBox(nameStack.Peek(  ))   ' Displays "Beethoven"     MsgBox(nameStack.Pop(  ))    ' Displays "Beethoven"     MsgBox(nameStack.Pop(  ))    ' Displays "Mozart"     ' ----- Remove the remaining items.     MsgBox(nameStack.Count)    ' Displays 1 (for Chopin)     nameStack.Clear(  ) 

Version Differences

Visual Basic 2005 adds support for generics to several collection-style classes, including the Stack class. The version of the Stack class that supports generics appears in the System.Collections.Generic namespace. Generics are discussed in Chapter 10.

See Also

Collection Class, Hashtable Class, Queue Class




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net