Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: Suppose we define an IntArrayStack class that implements the interface Sta

ID: 3844797 • Letter: J

Question

JAVA:

Suppose we define an IntArrayStack class that implements the  interface Stack<Integer >. (See exercise 307.)   Our class has instance variables  

   private  Integer [] theArray; // To hold the values in the stack
   private  int topIndex; // For an empty stack, topIndex = -1
public final int maxSize; // the size of theArray after it gets allocated

Implement the pop method . (You should be able to figure out what the method header looks like.)

In the case of a empty stack, throw a java.util.EmptyStackException. ( https://docs.oracle.com/javase/7/docs/api/java/util/EmptyStackException.html )

Otherwise decrement topIndex.

Explanation / Answer

Since the interface definition is not given in the question, assuming the following structure.

public interface Stack<T> {

   public void push(T value);

   public T pop();

   public T peek();

   public boolean isEmpty();

}

The pop( ) method is shown below along with push() and isEmpty()

==============

import java.util.EmptyStackException;

public class IntArrayStack implements Stack<Integer>{

   private Integer [] theArray; // To hold the values in the stack

   private int topIndex; // For an empty stack, topIndex = -1

   public final int maxSize = 100; // the size of theArray after it gets allocated

  

   public IntArrayStack()

   {

       theArray = new Integer[maxSize];

       topIndex = -1;

   }

  

   @Override

   public void push(Integer value) {

       if(topIndex == maxSize-1)

           throw new RuntimeException("Stack is full");

       topIndex++;

       theArray[topIndex] = value;

   }

  

   @Override

   public boolean isEmpty() {

       return topIndex == -1;

   }

   @Override

   public Integer pop() {

       if(isEmpty())

           throw new EmptyStackException();

      

       Integer value = theArray[topIndex];

       topIndex--;

       return value;

   }

   @Override

   public Integer peek() {

       // TODO Auto-generated method stub

       return null;

   }

}