/** * An implementation of a stack using an underlying array * * @param Generic * @author gtowell * Created: Feb 14, 2020 * Modified: Oct 6, 2020 * Modified: August 6, 2021 */ public class ArrayStack implements StackIntf { /** The default capacity of the stack */ private static final int DEFAULT_CAPACITY = 40; /** The number of items in the stack */ private int size; /** The array used to hold the stack items */ private K[] underlyingArray; /** * Create a stack with the default capacity */ public ArrayStack() { this(DEFAULT_CAPACITY); } /** * Create a stack with the given capacity * * @param capacity the max number items the stack can hold. */ @SuppressWarnings("unchecked") public ArrayStack(int capacity) { size = 0; underlyingArray = (K[]) new Object[capacity]; } @Override public boolean isEmpty() { return size == 0; } @Override public K push(K e) { // TO BE WRITTEN return null; } @Override public K peek() { if (size > 0) { return underlyingArray[size - 1]; } return null; } @Override public K pop() { // TO BE WRITTEN return null; } @Override public int size() { return size; } @Override public void clear() { // TO BE WRITTEN } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{ "); for (int i = 0; i < size; i++) { sb.append(underlyingArray[i]); sb.append(" "); } sb.append("}"); return sb.toString(); } /** * Illustrate stack operations and usage. * * @param args */ public static void main(String[] args) { ArrayStack stack = new ArrayStack<>(); stack.push(5); System.out.println("Push 5: " + stack); stack.push(3); stack.push(7); stack.push(2); System.out.println("Push 3, then 7, then 2: " + stack); System.out.println("Size: " + stack.size()); System.out.println("Pop:" + stack.pop() + " " + stack); System.out.println("Empty?: " + stack.isEmpty()); System.out.println("Pop:" + stack.pop() + " " + stack); stack.clear(); System.out.println("Stack cleared\nEmpty?: " + stack.isEmpty()); } }