package stack;

public class StackFixedSizeArray<E> extends AbstractStack<E> {

	private static final int INITIAL_SIZE = 8;
	protected E[] elements;
	protected int nbElements;

	public StackFixedSizeArray(int size) {
		if (size < 0) {
			size = 0;
		}
		this.elements = (E[]) new Object[size];
		this.nbElements = 0;
	}

	public StackFixedSizeArray() {
		this(INITIAL_SIZE);
	}

	@Override
	public boolean isEmpty() {
		return this.nbElements == 0;
	}

	@Override
	public void pop() throws EmptyStackException {
		if (!this.isEmpty()) {
			this.elements[--this.nbElements] = null; // sinon le ramasse-miettes
													// ne peut pas libérer la
													// mémoire
		} else {
			throw new EmptyStackException();
		}
	}

	@Override
	public E peek() throws EmptyStackException {
		if (!this.isEmpty()) {
			return (E) this.elements[this.nbElements - 1];
		} else {
			throw new EmptyStackException();
		}
	}

	@Override
	public void push(E element) throws FullStackException {
		if (this.nbElements != this.elements.length) {
			this.elements[this.nbElements++] = element;
		} else {
			throw new FullStackException();
		}

	}

	@Override
	public Stack<E> clone() {
		StackFixedSizeArray<E> stack = new StackFixedSizeArray<E>(
				elements.length);
		for (int i = 0; i < this.nbElements; i++) {
			stack.elements[i] = this.elements[i];
		}
		stack.nbElements = this.nbElements;
		return stack;
	}

}
