JAVA: Suppose we define an IntArrayStack class that implements the interface Sta
ID: 3844796 • 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 push method . (You should be able to figure out what the method header looks like.)
In the case of a full stack, throw RuntimeException with the message "Stack is full."
Otherwise increment topIndex and assign the method 's parameter to theArray at the new topIndex.
Explanation / Answer
Since the question does not include the code for java interface Stack<T>, I have assumed the following structure for the same.
public interface Stack<T> {
public void push(T value);
public T pop();
public T peek();
public boolean isEmpty();
}
If there are any changes to method names , the same should be changed in the IntArrayStack class also. All the methods in the interface should be present in the class IntArrayStack.
Also since only push() has been asked to implemented , only the push () method is implemented in the class IntArrayStack. Other methods are yet to be implemented.
package stack;
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) {
// check if the stack is full
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() {
// TODO Auto-generated method stub
return null;
}
@Override
public Integer peek() {
// TODO Auto-generated method stub
return null;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.