The following is an implementation of an array based stack. It also includes sup
ID: 3684989 • Letter: T
Question
The following is an implementation of an array based stack. It also includes support for iteration. Although the iteration works properly, this is not the best engineered iterator. Carefully find and fix one engineering issue with the iterator. Hint: failing silently may not be the best approach...
public class ArrayStack<T> implements StackADT<T>, Iterable<E> {
private int top;
private T[] stack;
public ArrayStack() {
top = 0;
stack = (T[])(new Object[1000]); //no resize
}
public void push(T element) {
stack[top] = element;
top++;
}
public T pop() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top] = null;
return result;
}
//omitted: peek, isEmpty(), and size.
public Iterator<E> iterator() {
return new ReverseArrayIterator();
}
//note: intentionally no modChange; not a bug.
private class ReverseArrayIterator implements Iterator<E> {
private int i = top;
public boolean hasNext() {
return i > 0;
}
public E next() {
return data[--i];
}
public void remove() { }
}
}
Explanation / Answer
I found issues in the above implementation of array stack .
1) if stack full then it is required to throw an exception has shown below.
public void push(T element) {
if (isFull())
throw new FullCollectionException("stack");
stack[top] = element;
top++;
}
2) when "implements" used to implement interfaces which are defined in actual method implementation but
public Iterator<E> iterator() {
return new ReverseArrayIterator();
}
this method implemented in another class not in
private class ReverseArrayIterator implements Iterator<E> .
but not implemented in this class.
i found these 2 issues in the above implementation,,if any thing more needed comment...
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.