Reputation: 11
First of all, I apologise if this is a really obvious question or if I'm not looking at it correctly. I've been instructed to "extend the stack to be dynamic". I've been given specific instructions on how to do this, namely:
Make a new array tmp of twice the size of the current array
Copy all elements the current array (called S in the lecture notes) into tmp
Set S = tmp;
The block of code which should do this is to be placed into the push() method, replacing the exception throw section.
The problem is, I have no idea what kind of array I should be using (generics have only recently introduced to me and I don't quite understand them as much as I think I should). Is there something obvious I'm missing or do I just not understand this properly?
I didn't write the majority of this code, only the pop(), push() and top() methods.
public class ArrayStack<E> implements Stack<E> {
private E[] S;
private int top;
private int capacity;
private static int DEFAULT_SIZE = 100;
public ArrayStack(int size){
capacity = size;
S = (E[]) new Object[size];
top = -1;
}
public ArrayStack(){
this(DEFAULT_SIZE);
}
public E pop() throws StackException{
if(isEmpty())
throw new StackException("stack is empty");
return S[top--];
}
public void push(E e) throws StackException{
if (size() == capacity)
throw new StackException("Stack is full");
S[++top] = e;
}
public E top() throws StackException{
if(isEmpty())
throw new StackException("Stack is empty");
return S[top];
}
Upvotes: 1
Views: 198
Reputation: 3078
Looking at your code, it appears that the array should be of E
objects.
Using Java Generics, you can create this array with (E[]) new Object[2 * initial_size]
The instructions want you to look at the code segment below in push
if (size() == capacity)
throw new StackException("Stack is full");
and without giving too much away as this is an assignment to do
if (size() == capacity)
Make a new array tmp of twice the size of the current array
Copy all elements the current array (called S in the lecture notes) into tmp
S = tmp;
Upvotes: 1