MyArrayListStack Program
Description
This program builds an ArrayList based generic stack data structure.Associated Concepts:
Stack
Algorithm:
StackInterface Java interface
MyArrayListStack class
Client program
EmptyStackException class
It defines a Java interface StackInterface which includes
five abstract methods.
push(), pop(), peek(), size(), and isEmpty().
MyArrayListStack class
It implements StackInterface.
Two private data members: a generic ArrayList object and a variable called top to indicate the number of the objects in the stack.
Constructor:
size(), isEmpty(), push(), peek(), pop(), and toString() methods.
size() method
isEmpty() method
void push(E object) method
E peep() method
E pop() method
String toString() method
Two private data members: a generic ArrayList object and a variable called top to indicate the number of the objects in the stack.
Constructor:
Initialize the data members:
- Create the generic ArrayList object.
- Set the variable top to -1.
- Create the generic ArrayList object.
- Set the variable top to -1.
size(), isEmpty(), push(), peek(), pop(), and toString() methods.
size() method
Return the number of objects in the stack.
isEmpty() method
Return true if the stack is empty; false otherwise.
void push(E object) method
1. Increment the value of top variable by 1.
2. Add the object onto the top of the stack.
2. Add the object onto the top of the stack.
E peep() method
1. Check for the empty stack.
2. Return the object at the top of the stack.
2. Return the object at the top of the stack.
E pop() method
1. Check for the empty stack.
2. Remove the top object from the stack.
3. Decrement the value of top variable.
4. Return the removed object.
2. Remove the top object from the stack.
3. Decrement the value of top variable.
4. Return the removed object.
String toString() method
1. Declare a string to store the result.
2. In a loop, retrieve each object in the stack and add it to the result.
3. Return the result after the loop is ended.
2. In a loop, retrieve each object in the stack and add it to the result.
3. Return the result after the loop is ended.
Client program
Create a MyArrayListStack object.
Call the methods defined in the MyArrayListStack class to test them.
Call the methods defined in the MyArrayListStack class to test them.
EmptyStackException class
Extend the RuntimeException class.
Invoke the superclass' constructor in the constructor.
Invoke the superclass' constructor in the constructor.
Source Code
StackInterface classMyArrayListStack class
Client program
EmptyStackException class