Java Reference
In-Depth Information
Let us revise the stack class in Section 11.13, Case Study: A Custom Stack Class, to gener-
alize the element type with a generic type. The new stack class, named GenericStack , is
shown in Figure 19.4 and is implemented in Listing 19.1.
GenericStack<E>
-list: java.util.ArrayList<E>
An array list to store elements.
+GenericStack()
+getSize(): int
+peek(): E
+pop(): E
+push(o: E): void
+isEmpty(): boolean
Creates an empty stack.
Returns the number of elements in this stack.
Returns the top element in this stack.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
Returns true if the stack is empty.
F IGURE 19.4
The GenericStack class encapsulates the stack storage and provides the
operations for manipulating the stack.
L ISTING 19.1
GenericStack.java
1 public class GenericStack<E> {
2
generic type E declared
generic array list
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
3
4
public int getSize() {
getSize
5
return list.size();
6 }
7
8
public E peek() {
peek
9
return list.get(getSize() - 1 );
10 }
11
12 public void push(E o) {
13 list.add(o);
14 }
15
16 public E pop() {
17 E o = list.get(getSize() - 1 );
18 list.remove(getSize() - 1 );
19
push
pop
return o;
20 }
21
22
public boolean isEmpty() {
isEmpty
23
return list.isEmpty();
24 }
25
26 @Override
27
public String toString() {
28
return "stack: " + list.toString();
29 }
30 }
The following example creates a stack to hold strings and adds three strings to the stack:
GenericStack<String> stack1 = new GenericStack<>();
stack1.push( "London" );
stack1.push( "Paris" );
stack1.push( "Berlin" );
 
 
Search WWH ::




Custom Search