All pastes #935692 Raw Edit

Miscellany

public text v1 · immutable
·published 2008-03-09 21:01 UTC
rendered paste body
import java.util.NoSuchElementException;


public class TokenArrayStack implements TokenStack {
	
	Token[] tarray;
	
	/**
	 * Default Token Array Stack constructor
	 *
	 */
	public TokenArrayStack(){
		this(10);
	}
	
	public TokenArrayStack(int size){
		tarray = new Token[size];
	}

  /**
   * Tells if the stack is empty.
   *
   * @return <code>true</code> if the stack is empty, <code>false</code>
   *         otherwise.
   */
	public boolean isEmpty() {
		for(int i = 0; i < tarray.length; i++){
			if(tarray[i] != null){
				return false;
			}
		}
		return true;
	}

  /**
   * 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 {
			Token elem = tarray[0];
			for(int i = 1; i < tarray.length; i++){
				tarray[i-1] = tarray[i];
			}
		return elem;
		}
	}


  /**
   * 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(tarray[tarray.length-1] != null) {
			Token[] newarray;
			newarray = new Token[tarray.length+1];
			newarray[0] = elem;
			for(int i = 1; i < tarray.length+1; i++){
				newarray[i] = tarray[i-1];
			}
			tarray = newarray;
		}
		else {
			for(int i = tarray.length; i < 0; i--){
				tarray[i] = tarray[i-1];
			}
		}
		return elem;
	}

  /**
   * Returns the size of the stack.
   *
   * @return a non-negative number
   */
	public int size() {
		for(int i = 0; i < tarray.length; i++){
			if(tarray[i] == null){
				return i;
			}
		}
		return tarray.length;
	}

}