Question: Modify the class ArrayStack to use a dynamic array. This new class DynamicArrayStack has a constant DEFAULT_INC with the value 25. When the array is

Modify the class ArrayStack to use a dynamic array. This new class DynamicArrayStack has a constant DEFAULT_INC with the value 25. When the array is full, a new array is created with size DEFAULT_INC more than the previous array and then filled with the elements from the previous array. Similarly, when the array has DEFAULT_INC elements less than its capacity, it needs to be automatically resized. Make the necessary changes, particularly in pop, push and clear, and in the constructor (the minimal size of an array is DEFAULT_INC).

ArrayStack.java

public class ArrayStack implements Stack { // Instance variables private E[] elems; // Used to store the elements of this ArrayStack private int top; // Designates the first free cell @SuppressWarnings( "unchecked" ) // Constructor public ArrayStack( int capacity ) { elems = (E[]) new Object[ capacity ]; top = 0; } // Returns true if this ArrayStack is empty public boolean isEmpty() { // Same as: // if ( top == 0 ) { // return true; // } else { // return false; // } return ( top == 0 ); } // Returns the top element of this ArrayStack without removing it public E peek() { // pre-conditions: ! isEmpty() return elems[ top-1 ]; } // Removes and returns the top element of this stack public E pop() { // pre-conditions: ! isEmpty() // *first* decrements top, then access the value! E saved = elems[ --top ]; elems[ top ] = null; // scrub the memory! return saved; } // Puts the element onto the top of this stack. public void push( E element ) { // Pre-condition: the stack is not full // *first* stores the element at position top, then increments top elems[ top++ ] = element; } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!