I've recently been writing simple data structures, even though they exist in the library it helps me understand them a lot better.
public class Stack<E>
{
private int capacity;
private E[] data;
private int top;
/**
* Default Constructor where the stack size is initially
* set to 1000 elements.
*/
public Stack(int capacity) {
this.capacity = capacity;
this.data = (E[])new Object[capacity];
top = -1;
}
public Stack() {
this(1000);
}
public int size() {
return top + 1;
}
public boolean isEmpty() {
return top == -1;
}
public E top() throws EmptyADTException {
if(isEmpty())
throw new EmptyADTException("Nothing in the stack!");
return data[top];
}
public void push(E obj) {
if(data.length == size())
throw new IllegalStateException("Stack is full!");
data[++top] = obj;
}
public E pop() throws EmptyADTException {
if(isEmpty())
throw new EmptyADTException("Nothing in the stack!");
E popObj = data[top];
data[top--] = null;
return popObj;
}
}
I know that there are drawbacks to using an array-based stack, because of the limited size. Although, in the long run, it is more efficient if the time per operation isn't an issue, when compared to a linked-list implementation. I've also heard of people now using something called a VList
.
I was wondering, is there any way I can improve this code whilst still using an array-based stack?
data[top--] = null;
. Thetop--
is part of the stack core implementation (if you don't do it it does not work), whiledata[...] = null
is not mandatory, and is just cleaning things to make sure memory can be freed. You should split those 2. \$\endgroup\$