As an exercise, I wanted to make an array implementation of Stack
, including most of the methods from the native Java Stack
.
I'd like to know the following:
- Does the code follow good programming principles?
- Is the code readable/understandable?
- Are there any redundant fields/operations?
- Is there a way to further improve the code?
- Should I reduce the capacity of the stack at some point? Testing the native Java Stack, it doesn't seem to do any size reduction, except with
trim()
.
Note: I know Javadoc is missing, but I am only just beginning to read into that.
import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.Random;
@SuppressWarnings("unchecked")
public class ArrayStack<T> {
private T[] data;
private int numElements;
private static final int INITIAL_CAPACITY = 10;
public ArrayStack() {
data = (T[]) new Object[INITIAL_CAPACITY];
}
private void enlarge() {
T[] temp = Arrays.copyOf(data, data.length);
data = (T[]) new Object[data.length * 2];
for (int i = 0; i < temp.length; i++) {
data[i] = temp[i];
}
}
public void push(T element) {
if (numElements == data.length) {
enlarge();
}
data[numElements] = element;
numElements++;
}
public T peek() {
if (isEmpty()) throw new EmptyStackException();
return data[numElements - 1];
}
public T pop() {
if (isEmpty()) throw new EmptyStackException();
T element = data[--numElements];
data[numElements] = null;
return element;
}
public boolean isEmpty() {
return (numElements == 0);
}
public int capacity() {
return data.length;
}
public int size() {
return numElements;
}
public void clear() {
for (int i = 0; i < numElements; i++) {
data[i] = null;
}
numElements = 0;
}
}