Java Reference
In-Depth Information
1
// Fig. 20.7: Stack.java
2
// Stack generic class declaration.
3
import java.util.ArrayList;
4
5
public class Stack<T>
6
{
7
private final ArrayList<T> elements; // ArrayList stores stack elements
8
9
// no-argument constructor creates a stack of the default size
10
public Stack()
11
{
12
this ( 10 ); // default stack size
13
}
14
15
// constructor creates a stack of the specified number of elements
16
public Stack( int capacity)
17
{
18
int initCapacity = capacity > 0 ? capacity : 10 ; // validate
19
elements = new ArrayList<T>(initCapacity); // create ArrayList
20
}
21
22
// push element onto stack
23
public void push(T pushValue)
24
{
25
elements.add(pushValue); // place pushValue on Stack
26
}
27
28
// return the top element if not empty; else throw EmptyStackException
29
public T pop()
30
{
31
if (elements.isEmpty()) // if stack is empty
32
throw new EmptyStackException( "Stack is empty, cannot pop" );
33
34
// remove and return top element of Stack
35
return elements.remove(elements.size() - 1 );
36
}
37
} // end class Stack<T>
Fig. 20.7 | Stack generic class declaration.
Method push (lines 23-26) uses ArrayList method add to append the pushed item
to the end of the ArrayList elements . The last element in the ArrayList represents the
top of the stack.
Method pop (lines 29-36) first determines whether an attempt is being made to pop
an element from an empty Stack . If so, line 32 throws an EmptyStackException (declared
in Fig. 20.8). Otherwise, line 35 in Fig. 20.7 returns the top element of the Stack by
removing the last element in the underlying ArrayList .
Class EmptyStackException (Fig. 20.8) provides a no-argument constructor and a
one-argument constructor. The no-argument constructor sets the default error message,
and the one-argument constructor sets a custom error message.
As with generic methods, when a generic class is compiled, the compiler performs era-
sure on the class's type parameters and replaces them with their upper bounds. For class
 
Search WWH ::




Custom Search