Stacks and Queues Gregory D. Weber CSCI C243 Data Structures
Principal Points 1. The Stack interface: how to declare it, what it does. 2. Generics: why they were added to Java, how to use them. 3. The call stack: how it supports execution of method calls. 4. Exceptions: what are they, how to use them. 5. The Queue interface: how to declare it, what it does.
Stacks and Queues Stacks and queues are similar: both are collections ordered by time of insertion. Differences: stacks allow access to the most recently inserted element; queues, least recently inserted. We study the stack and queue ADTs, deferring implementations
4.1 Stack Interface v. 1 Top of stack Fig. 4-1, p. 88 Operations: push, pop, peek, isempty LIFO (Last In, First Out): remove elements in opposite order from insertion The interface declaration, version 1 (non-generic, i.e., a stack of Objects): Fig. 4-2 pp. 88 89
The Class java.util.stack Drake presents stack ADT as an interface Java standard library includes class java.util.stack Find its documentation in Java API documentation. How does it compare? Still an abstract data type for us
Generics Motivation Generic types (classes and interfaces) introduced in Java 1.5. Parametric types A generic type has one or more type parameters, typically specifying the types of elements it can contain. public class Stack<E> In constructors and methods E For stacks, E represents the type of elements To make a stack of Integers: Stack<Integer> s = new Stack<Integer>(); Default: E is Object
Generic Stack Interface (v. 2) Code, Fig. 4-2 p. 90 Compare to version 1 Instantiating the generic type: error on p. 89 Stack<Die> s = new Stack<Die>(); We cannot instantiate an interface We must instantiate a class Stack<Die> s = new StackImpl<Die> ();
Evaluating Generic Types Advantages Stricter type checking Cannot push Beetle onto Stack<Die> Avoid ugly casts Stack mystack =...; mystack.push(new Beetle()); Beetle tony = (Beetle) (mystack.pop()); Disadvantages More syntax, additional complexity Type parameters exist only at compile time Generic types are an option
Example Reversing the order of words in a message, using a stack: Reverse.java
4.2 The Call Stack How to call methods with local variables? main (args) A(x, y) B(y, z) C(z, w) Two problems arise: 1. Avoid conflict of common variable names 2. Where should each method return to?
Recursive Method Calls (same problems, more intense) main(args) fact(n) fact(n) fact(n)
Solution: the Call Stack A stack of call frames (activation records) Each call frame represents a method call Stores parameters, other local variables Stores return address Fig. 4-16 p. 99: explain in detail. Identify the call frames. Usually ignore the call stack, but... It sheds light on recursion and Java error messages
Interpreting a Stack Trace See Fig. 4-17 p. 100 Interpret the stack trace. Focus programmer s attention on two methods Where the exception occurred The method that called that one
Lab 2: Postfix Calculator p. 116, Project 4.20 Demonstrate the desktop calculator dc p prints top of stack( peek ) [Hello world]p prints Hello world Control-D to exit
Break
4.3 Exceptions Graceful handling of anomalies Compare with assertions Errors Throwing Catching Not catching
Exceptions Are Objects Many kinds Exception ArithmeticException NullPointerException ArrayIndexOutOfBoundsException Defining our own public class IllegalMoveException extends Exception { }
Throwing Exceptions 1. Declare the method throws RottenEggException 2. Javadoc comment the exception with keyword @throws 3. Write code to create and throw exception if (...) throw new RottenEggException(); 4. Example: deal method in IdiotsDelight.java (Fig. 4-20 p. 102)
Calling Methods That Throw Exceptions Two choices: 1. Pass the buck Caller must declare throws RottenEggException unless it s a RuntimeException 2. Catch exception using a try/catch statement: try {... } catch (RottenEggException e) {... // handle exception e }
Things to Do with a Caught Exception Try to correct the error Print stack trace; exit with error code: e.printstacktrace(); System.exit(1); Return codes: 0 = okay, true; non-zero = error, false
Examining the Return Code Using bash or similar shells With logical operators $ java MyRottenEggClass echo "something s wrong" $ java MyRottenEggClass && echo "success!" With the if statement $ if java MyRottenEggClass; then echo "Hooray!" else echo "Boo-hoo" fi Examining the shell variable $? $ java MyRottenEggClass $ echo $?
A Few of the Exception Classes (page 107) Exception IllegalMoveException RuntimeException EmptyStructureException ArithmeticException NullPointerException ArrayIndexOutOfBoundsException Methods need not declare throwing RuntimeExceptions
4.4 Queues Queues are FIFO collections First In, First Out Opposite of stack
Queue Interface Queue.java (page 109, Figure 4-30)
Queue Methods Preferred names: enqueue for add, and dequeue for remove. How to remember: enqueue as in enter (enter queue) dequeue as in depart (depart queue) Could add a front method, analogous to peek for stacks
A Queue Example A queue to manage printing: Printing.java