Java Reference
In-Depth Information
10.6 Case Study: Designing a Class for Stacks
This section designs a class for modeling stacks.
Key
Point
Recall that a stack is a data structure that holds data in a last-in, first-out fashion, as shown in
FigureĀ 10.11.
stack
Data1
Data2
Data3
Data3
Data2
Data1
Data2
Data1
Data1
Data3
Data2
Data1
Data2
Data1
Data1
F IGURE 10.11
A stack holds data in a last-in, first-out fashion.
Stacks have many applications. For example, the compiler uses a stack to process method
invocations. When a method is invoked, its parameters and local variables are pushed into a
stack. When a method calls another method, the new method's parameters and local variables
are pushed into the stack. When a method finishes its work and returns to its caller, its associ-
ated space is released from the stack.
You can define a class to model stacks. For simplicity, assume the stack holds the int
values. So name the stack class StackOfIntegers . The UML diagram for the class is shown
in FigureĀ 10.12.
VideoNote
The StackOfIntegers class
StackOfIntegers
-elements: int[]
-size: int
An array to store integers in the stack.
The number of integers in the stack.
+StackOfIntegers()
+StackOfIntegers(capacity: int)
+empty(): boolean
+peek(): int
Constructs an empty stack with a default capacity of 16.
Constructs an empty stack with a specified capacity.
Returns true if the stack is empty.
Returns the integer at the top of the stack without
removing it from the stack.
Stores an integer into the top of the stack.
Removes the integer at the top of the stack and returns it.
Returns the number of elements in the stack.
+push(value: int): void
+pop(): int
+getSize(): int
F IGURE 10.12
The StackOfIntegers class encapsulates the stack storage and provides
the operations for manipulating the stack.
Suppose that the class is available. The test program in Listing 10.7 uses the class to cre-
ate a stack (line 3), store ten integers 0 , 1 , 2 , . . . , and 9 (line 6), and displays them in reverse
order (line 9).
L ISTING 10.7
TestStackOfIntegers.java
1 public class TestStackOfIntegers {
2
public static void main(String[] args) {
3
StackOfIntegers stack = new StackOfIntegers();
create a stack
 
 
 
Search WWH ::




Custom Search