I have created a simple array-based Stack class with some methods like the actual Stack in Java.
I am testing this for mistakes, but since I am learning Java, my tests may not be as comprehensive as they should.
import java.util.*;
public class SJUStack<E> {
// Data Fields
private E[] theData;
private int topOfStack = -1;
private static final int INITIAL_CAPACITY = 10;
private int size = 0;
private int capacity = 0;
// Constructors
public SJUStack(int initCapacity) {
capacity = initCapacity;
theData = (E[]) new Object[capacity];
}
public SJUStack() {
this(INITIAL_CAPACITY);
}
// Methods
public E push(E e) {
if(size == capacity) {
reallocate();
}
theData[size] = e;
size++;
topOfStack++;
return e;
} // End push(E e) method
public E peek() {
if(empty()) {
throw new EmptyStackException();
}
return theData[topOfStack];
} // End peek() method
public E pop() {
E result = peek();
theData[topOfStack] = null;
size--;
topOfStack--;
if(size <= (capacity/4) && capacity >= INITIAL_CAPACITY) {
shrink();
}
return result;
} // End pop() method
public boolean empty() {
return size == 0;
} // End empty() method
private void reallocate() {
capacity *= 2;
theData = Arrays.copyOf(theData, capacity);
} // End reallocate() method
private void shrink() {
capacity /= 2;
theData = Arrays.copyOf(theData, capacity);
} // End shrink() method
public String toString() {
return Arrays.toString(theData);
} // End toString() method
public int size() {
return size;
} // End size() method
}
Stack
interface. \$\endgroup\$