ArrayStringStack.java
package ch.hslu.exercises.sw02.ex3;
import java.util.NoSuchElementException;
public final class ArrayStringStack implements Stack<String> {
private final String[] array;
private int top;
public ArrayStringStack(final int size) {
array = new String[size];
top = size - 1;
}
@Override
public int size() {
return array.length;
}
@Override
public String peek() {
if (isEmpty()) {
throw new NoSuchElementException("The Stack is empty!");
}
return array[top + 1];
}
@Override
public String pop() {
if (isEmpty()) {
throw new NoSuchElementException("The Stack is empty!");
}
String topString = array[top + 1];
array[top + 1] = null;
top++;
return topString;
}
@Override
public void push(final String element) {
if (isFull()) {
throw new IndexOutOfBoundsException("The stack is full!");
}
array[top] = element;
top--;
}
@Override
public boolean isEmpty() {
return size() == top + 1;
}
@Override
public boolean isFull() {
return top == -1;
}
}