Question #73079

3. Use a simple array to implement stack.

Expert's answer

Question #73079, Programming & Computer Science / Java | JSP | JSF | for completion

Use a simple array to implement stack.

The solution is based on the example from the book "Effective Java" by Joshua Bloch:


public class Stack<E> {
    private E[] arr = null;
    private int CAPACITY;
    private int top = -1;
    private int size = 0;
    @SuppressWarnings("unchecked")
    public Stack(int cap) {
        this.CAPACITY = cap;
        this.arr = (E[]) new Object[cap];
    }
    public E pop() {
        if (this.size == 0) {
            return null;
        }
        this.size--;
        E result = this.arr[top];
        this.arr[top] = null; //prevent memory leaking
        this.top--;
        return result;
    }
    public boolean push(E e) {
        if (isFull()) {
            return false;
        }
        this.size++;
        this.arr[++top] = e;
        return true;
    }
    public boolean isFull() {
        return this.size == this.CAPACITY;
    }
    public boolean isEmpty() {
        return this.size == 0;
    }
    public String toString() {
        if (this.isEmpty()) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < this.size; i++) {
            sb.append(this.arr[i]).append(", ");
        }
        sb.setLength(sb.length()-2);
        return sb.toString();
    }
}


Testing the class Stack:


public class Main {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>(10);
        stack.push("One");
        stack.push("Two");
        stack.push("Three");
        stack.push("Four");
        stack.push("Five");
        stack.push("Six");
        stack.push("Seven");
        stack.push("Eight");
        stack.push("Nine");
        stack.push("Ten");
        System.out.println(stack);
        while(!stack.isEmpty()){
            System.out.println(stack.pop());
        }
    }
}


Result:</string>



Answer provided by AssignmentExpert.com

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS