StackRA.java (1709B)
1 package collections; 2 3 public class StackRA<T> implements StackInterface<T>{ 4 5 protected T []items; 6 protected int numItems; 7 8 public StackRA() { 9 items = (T[]) new Object[3]; 10 numItems = 0; 11 } 12 13 public boolean isEmpty() { 14 return (numItems == 0); 15 } 16 17 public int size() { 18 return numItems; 19 } 20 21 public void popAll() { 22 items = (T[]) new Object[3]; 23 numItems = 0; 24 } 25 26 public void push (T item) 27 throws StackException { 28 29 if (numItems == items.length) { 30 resize(); 31 } 32 items[numItems++] = item; 33 } 34 35 public T pop() 36 throws StackException { 37 if (numItems != 0) { 38 T item = items[numItems -1]; 39 items[numItems-1] = null; 40 numItems --; 41 return item; 42 } 43 else { 44 throw new StackException("StackException: Stack is empty on pop()"); 45 } 46 } 47 48 public T peek() 49 throws StackException { 50 if (numItems != 0) { 51 return items[numItems - 1]; 52 } 53 else { 54 throw new StackException("StackException: Stack is empty on peek()"); 55 } 56 } 57 58 public void resize() { 59 T []tmp; 60 tmp = (T[]) new Object[numItems*2 + 1]; 61 for (int i = 0; i < items.length; i++) { 62 tmp[i] = items[i]; 63 } 64 items = tmp; 65 } 66 67 @Override 68 public String toString() { 69 String result = "Stack of size " + numItems + " has the following items : "; 70 71 for (int i = 0; i < numItems; i++) { 72 if (items[i] != null) 73 result += items[i] + " "; 74 } 75 76 return result; 77 } 78 79 }