Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Alice

StackExample


ArrayStack.java

import java.util.Iterator;

/**
 * A simple Stack implementation based on an array
 * 
 * @author Chuck Cusack
 * @version 1.0, February 2008
 */
public class ArrayStack<T> implements StackInterface<T> {
	T[]	theElements;
	int	top;

	public ArrayStack(int capacity) {
		// The following code is illegal in Java.
		// You cannot create an array of a generic type in Java
		// theElements = new T[3];

		// There are two "hacks" that allow you to get an array of
		// generic type. Both give compiler warnings.
		theElements = (T[]) new Object[capacity];
		// theElements = (T[])Array.newInstance(theElements.getClass(),3);

		top = -1;
	}

	public boolean isEmpty() {
		return top == -1;
	}

	public boolean isFull() {
		return top == theElements.length - 1;
	}

	public boolean push(T item) {
		if (!isFull()) {
			top++;
			theElements[top] = item;
			return true;
		} else {
			return false;
		}
	}

	public T pop() {
		if (!isEmpty()) {
			top--;
			// Why does this work?
			return theElements[top + 1];
		} else {
			return null;
		}
	}

	public T peek() {
		if (isEmpty()) {
			return null;
		} else {
			return theElements[top];
		}
	}

	public Iterator<T> iterator() {
		// Here is a convenient way to get an iterator for an array
		// Unfortunately, this iterator goes in the reverse direction of
		// what we might want for a stack.
		// return Arrays.asList(theElements).iterator();

		// Instead we can implement our own iterator that
		// works in reverse order so it orders properly
		// for a stack.
		return new ArrayReverseIterator(theElements);
	}
}