Java Reference
In-Depth Information
delegation —the stack method invoked delegates the call to the appropriate List<T>
method. In particular, StackComposition<T> delegates calls to List<T> methods insert-
AtFront , removeFromFront , isEmpty and print . In this example, we do not show class
StackCompositionTest , because the only difference is that we change the type of the stack
from StackInheritance to StackComposition (lines 3 and 10 of Fig. 21.11).
1
// Fig. 21.12: StackComposition.java
2
// StackComposition uses a composed List object.
3
package com.deitel.datastructures;
4
5
public class StackComposition<T>
6
{
7
private List<T> stackList;
8
9
// constructor
10
public StackComposition()
11
{
12
stackList = new List<T>( "stack" );
13
}
14
15
// add object to stack
16
public void push(T object)
17
{
18
stackList.insertAtFront(object);
19
}
20
21
// remove object from stack
22
public T pop() throws EmptyListException
23
{
24
return stackList.removeFromFront();
25
}
26
27
// determine if stack is empty
28
public boolean isEmpty()
29
{
30
return stackList.isEmpty();
31
}
32
33
// output stack contents
34
public void print()
35
{
36
stackList.print();
37
}
38
} // end class StackComposition
Fig. 21.12 | StackComposition uses a composed List object.
21.6 Queues
Another commonly used data structure is the queue . A queue is similar to a checkout line
in a supermarket—the cashier services the person at the beginning of the line first . Other
customers enter the line only at the end and wait for service. Queue nodes are removed only
from the head (or front) of the queue and are inserted only at the tail (or end). For this reason,
 
 
Search WWH ::




Custom Search