Java Reference
In-Depth Information
687
Figure 13
A Queue
Stacks are used when a Ȓlast in, first outȓ rule is required. For example, consider an
algorithm that attempts to find a path through a maze. When the algorithm encounters
an intersection, it pushes the location on the stack, and then it explores the first
branch. If that branch is a dead end, it returns to the location at the top of the stack. If
all branches are dead ends, it pops the location off the stack, revealing a previously
encountered intersection. Another important example is the run-time stack that a
processor or virtual machine keeps to organize the variables of nested methods.
Whenever a new method is called, its parameters and local variables are pushed onto
a stack. When the method exits, they are popped off again. This stack makes
recursive method calls possible.
There is a Stack class in the Java library that implements the abstract stack type and
the push and pop operations. The following sample code shows how to use that
class.
Stack<String> s = new Stack<String>();
Search WWH ::




Custom Search