Principle 16.5.5. EFFECTIVE DESIGN: ADTs.
ADTs encapsulate and manage the difficult tasks involved in manipulating the data structure. But because of their extensibility, they can be used in a wide range of applications.
Queue
Class
Queue
class is also trivial to derive from List
(Figure 16.5.2). Here we just restrict operations to the insertAtRear()
and removeFirst()
methods (Listing 16.5.3). To test the methods of this class, we replace the push()
and pop()
operations of the last example to enqueue()
and dequeue()
, respectively (Listing 16.5.4). In this case, the letters of the test string will come out of the queue in the same order they went in—FIFO.Queue
’s enqueue()
and dequeue()
methods can use the List
’s insertAtRear()
and removeFirst()
methods, respectively.public class Queue extends List {
public Queue() {
super(); // Initialize the list
}
public void enqueue(Object obj) {
insertAtRear( obj );
}
public Object dequeue() {
return removeFirst();
}
}// Queue
Queue
ADT.public static void main(String argv[]) {
Queue queue = new Queue();
String string = "Hello this is a test string";
System.out.println("String: " + string);
for (int k = 0; k < string.length(); k++)
queue.enqueue( new Character(string.charAt(k)));
System.out.println("The current queue:");
queue.print();
Object o = null;
System.out.println("Dequeuing:");
while (!queue.isEmpty()) {
o = queue.dequeue();
System.out.print( o.toString() );
}
} // main()
Queue
ADT. Letters inserted in a queue come out in the same order they went in.Queue
ADT as a subclass of List
is given here. To test it, add code to the main method that enqueues every character in a string, then prints the queue, then de-queues all elements of the queue. (Note: the Character(char)
constructor has been deprecated. To create a Character
object, you can use the static method Character.valueOf(char)
instead.)peekLast()
method for the Queue
class. It should take no parameters and return an Object
. It should return a reference to the Object
stored in the last Node
of the queue without removing it.