Question: The class ArrayStack uses an array of fixed size and implements the interface Stack. Since the interface Stack has been modified to have the method

The class ArrayStack uses an array of fixed size and implements the interface Stack. Since the interface Stack has been modified to have the method clear(), the implementation of the class ArrayStack is faulty. (Try to compile it now without changing anything, what error do you see?). Since the class ArrayStack implements the interface Stack, it needs to have an implementation for all methods of the interface. Therefore, you will need to write a method void clear(). This method will remove all the elements from this stack (ArrayStack). The stack will be empty after this call. Use the class L6Q1 to test the implementation of the method clear().

ArrayStack.java

ublic 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; } } 

L6Q1.java

public class L6Q1 { public static void main( String[] args ) { Stack s; s = new ArrayStack( 10 ); for ( int i=0; i<10; i++ ) { s.push( "Elem-" + i ); } s.clear(); while ( ! s.isEmpty() ) { System.out.println( s.pop() ); } for ( int i=0; i<10; i++ ) { s.push( "** Elem-" + i ); } while ( ! s.isEmpty() ) { System.out.println( s.pop() ); } } } 

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!