I'm trying to understand this:
In java, Stack extends Vector. That's OK. It's a synchronized implementation. However, synchronization isn't always needed, in such cases, it's advised to use ArrayDeque.
But If Stack would have been built using composite pattern with LinkedList, wouldn't it have been better? LinkedList provides better performance for inserting and deleting. Additionally, arrays are fixed in size, anytime you need to increase the size of the list, you also need to reallocate a new array and copy the contents over. Finally, with LinkedList an implementation for Stack may be easier and more performant than array.
public class ListStack implements Stack {
private final List _list = new LinkedList();
public void push(Object value) {
_list.add(value);
}
public Object pop() throws EmptyStackException {
if(isEmpty()) {
throw new EmptyStackException();
}
return _list.delete(_list.size() - 1);
}
public Object peek() throws EmptyStackException {
Object result = pop();
push(result);
return result;
}
public void clear() {
_list.clear();
}
public int size() {
return _list.size();
}
public boolean isEmpty() {
return _list.isEmpty();
}
public void enqueue(Object value) {
push(value);
}
public Object dequeue() throws EmptyQueueException {
try {
return pop();
}catch (EmptyStackException ex) {
throw new EmptyStackException();
}
}
}