import java.util.NoSuchElementException;
public class TokenArrayStack implements TokenStack {
private Token[] tarray;
private int count;
/**
* Default Token Array Stack constructor
*
*/
public TokenArrayStack(){
this(10);
}
public TokenArrayStack(int size){
tarray = new Token[size];
count = 0;
}
/**
* Tells if the stack is empty.
*
* @return <code>true</code> if the stack is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
if(count == 0) return true;
return false;
}
/**
* Returns the token at the top of the stack.
*
* @return the {@link Token} instance at the top of the stack
* @throws java.util.NoSuchElementException
* if the stack is empty
*/
public Token peek() {
if(isEmpty()){
throw new NoSuchElementException();
}
else {
return tarray[0];
}
}
/**
* Removes and returns the token at the top of the stack.
*
* @return the {@link Token} instance at the top of the stack
* @throws java.util.NoSuchElementException
* if the stack is empty
*/
public Token pop() {
if(isEmpty()){
throw new NoSuchElementException();
}
else {
return tarray[count--];
}
}
/**
* Adds the given token to the top of the stack.
*
* @param elem the {@link Token} instance that must be added
* @return the <code>Token</code> instance that was added
*/
public Token push(Token elem) {
if(count == tarray.length) {
Token[] newarray = new Token[2*tarray.length];
for(int i = 0; i < tarray.length; i++){
newarray[i] = tarray[i];
}
tarray = newarray;
}
tarray[++count] = elem;
return elem;
}
/**
* Returns the size of the stack.
*
* @return a non-negative number
*/
public int size() {
return count;
}
}