Question
Add the following methods to the ArrayBoundedStack class, and create a test driver for each to show that they work correctly. In order to practice
Add the following methods to the ArrayBoundedStack class, and create a test driver for each to show that they work correctly. In order to practice your array related coding skills, code each of the methods by accessing the internal variables of the ArrayBoundedStack, not by calling the previously defined public methods of the class.
a. String toString() - creates and returns a string that correctly represents the current stack. Such a method could prove useful for testing and debugging the each
class and for testing and debugging applications that use the class. Assume each stack element already provided its own reasonable toString method.
public class ArrayBoundedStack
public ArrayBoundedStack() { elements = (T[]) new Object[DEFCAP]; }
public ArrayBoundedStack(int maxSize) { elements = (T[]) new Object[maxSize]; }
public void push(T element) // Throws StackOverflowException if this stack is full, // otherwise places element at the top of this stack. { if (isFull()) throw new StackOverflowException("Push attempted on a full stack."); else { topIndex++; elements[topIndex] = element; } }
public void pop() // Throws StackUnderflowException if this stack is empty, // otherwise removes top element from this stack. { if (isEmpty()) throw new StackUnderflowException("Pop attempted on an empty stack."); else { elements[topIndex] = null; topIndex--; } }
public T top() // Throws StackUnderflowException if this stack is empty, // otherwise returns top element of this stack. { T topOfStack = null; if (isEmpty()) throw new StackUnderflowException("Top attempted on an empty stack."); else topOfStack = elements[topIndex]; return topOfStack; }
public boolean isEmpty() // Returns true if this stack is empty, otherwise returns false. { return (topIndex == -1); }
public boolean isFull() // Returns true if this stack is full, otherwise returns false. { return (topIndex == (elements.length - 1)); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started