/** * GenericsArrayStack * Pila generica realizzata con array ridimensionabile * classe didattica * @author A. Luchetta * @version 5-Dic-2006 * @see GenericsStack */ public class GenericsArrayStack implements GenericsStack { private static int INITIAL_DIM = 1; private Object[] v; private int vSize; public GenericsArrayStack() { makeEmpty(); } /** rende vuoto il contenitore */ public void makeEmpty() { v = new Object[INITIAL_DIM]; vSize = 0; } /** @return true se il contenitore e' vuoto, false altrimenti */ public boolean isEmpty() { return vSize == 0; } /** @return numero di elementi nel contenitore */ public int size() { return vSize; } /** inserisce un elemento in cima alla pila @param o l’elemento da inserire */ public void push(T o) { if (vSize >= v.length) v = resize(v, 2 * v.length); v[vSize] = o; vSize++; } /** ispeziona l’elemento in cima alla pila @return l’elemento in cima alla pila @throws EmptyStackException se la pila e’ vuota */ public T top() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException(); return (T) v[vSize - 1]; } /** rimuove l’elemento dalla cima della pila @return l’elemento rimosso @throws EmptyStackException se la pila e’ vuota */ public T pop() throws EmptyStackException { T tmp = top(); v[vSize - 1] = null; vSize--; return tmp; } // ridimensionamento dinamico di array private Object[] resize(Object[] a, int length) { Object[] tmp = new Object[length]; int minLength = a.length < length ? a.length : length; for (int i = 0; i < minLength; i++) tmp[i] = a[i]; return tmp; } }