Array Implementation of Stack ADT
CPE 103 Lab Activity
For this lab you will be creating and testing an array
implementation
of a Stack
ADT.
1. Read the API for Java's Stack class: java.util.Stack.
2. Create a JUnit test class named StackTest that tests
the push(),
pop(), and empty() methods of java.util.Stack.
Be
sure to import java.util.Stack. Your tests must
demonstrate the correct functioning of a Stack of Strings. Test the
three methods and throwing of exception.
Run your tests and confirm they are working properly. Show
your
working unit tests to the instructor before continuing.
3. Design and build your own implementation of the Stack API that
uses
an array to represent the stack (not an ArrayList). You
only need to implement the three methods listed above. Your
class
must be generic.
Hints:
You may omit checking for a full array in the push()
method.
To make Stack a generic class, you must put the
formal type parameter after the class name, like this:
public class Stack<Element>
Stack has two private instance variables: an
array
of elements and an index of the top element.
Stack has one constructor that creates an empty
stack of some fixed capacity (you may choose the amount; declare it
as
a named constant kCapacity). To avoid getting
a
"generic array
creation" error, use this code idiom:
private Element[] myArray;
...
myArray = (Element[]) new
Object[kCapacity+1];
The compiler will produce an "unchecked
conversion" warning,
which you are permitted to ignore in this situation using
@SuppressWarnings({"unchecked"})
before the method.
4. When your Stack class compiles cleanly, remove the import
java.util.Stack; statement from your unit test class.
Voila,
it is now a test for your Stack class.
5. Correct any errors in your Stack class until it passes your
unit tests.
6. Modify your Balance.java program from the previous
lab
by removing the
import of java.util.Stack. Put
your Stack class in the same folder as Balance.java. Verify that
Balance JUnit test still pass with your new Stack class.
7. Be
sure each student has an @author tag in the source code.
Submit your Stack class to Web-CAT for automated grading.
8. (If time allows) In chapter 11 the author discusses a case study
at length, balanced-symbol checking. Download the source for
the author's program from chapter 11 into the same folder as your
Stack class. Tokenizer.java
Balance.java
Change the author's code to use your Stack class instead of
his: Remove import weiss.util.Stack.
Verify the program compiles without error.
Run the main method in the Balance class, open the BlueJ terminal
window, and provide some expressions to be evaluated. Verify the
correct output is produced. (Review chapter 11 if you forget what
input is required.)