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

Revise the program below class to implement it using an array rather than an Arr

ID: 3621545 • Letter: R

Question

Revise the program below class to implement it using an array rather than an ArrayList. You should check the array size before adding a new element to the stack. if the array is full, create a new array that doubles the current array size and copy the elements from the current array to the new array.

Program:

public class GenericStack<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<E>();

public int getSize() {
return list.size();
}

public E peek() {
return list.get(getSize() - 1);
}

public E push(E o) {
list.add(o);
return o;
}

public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}

public boolean isEmpty() {
return list.isEmpty();
}
}

Explanation / Answer

Dear, /** Array Implementation of a stack. */ public class ArrayStack { private int [] s; // Holds stack elements private int top; // Stack top pointer /** Constructor. @param capacity The capacity of the stack. */ public ArrayStack (int capacity) { s = new int[capacity]; top = 0; } /** The empty method checks for an empty stack. @return true if stack is empty. */ public boolean empty() { return top == 0; } /** The push method pushes a value onto the stack. @param x The value to push onto the stack. @exception StackOverflowException When the stack is full. */ public void push(int x) { if (top == s.length) throw new StackOverFlowException(); else { s[top] = x; top ++; } } /** The pop method pops a value off the stack. @return The value popped. @exception EmptyStackException When the stack is empty. */ public int pop() { if (empty()) throw new EmptyStackException(); else { top--; return s[top]; } } /** The peek method returns the value at the top of the stack. @return value at top of the stack. @exception EmptyStackException When the stack is empty. */ int peek() { if (empty()) throw new EmptyStackException(); else { return s[top-1]; } } } /** This class demonstrates the use of the ArrayStack class. */ public class ArrayStackDemo { public static void main(String [] arg) { String str; // Use for output ArrayStack st = new ArrayStack(5); str = "Pushing 10 20 onto the stack."; System.out.println(str); st.push(10); st.push(20); str = "Value at top of the stack is "; System.out.println(str + st.peek()); str = "Popping and printing all values:"; System.out.println(str); while (!st.empty()) System.out.print(st.pop() + " "); } } Hope this will help you

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote