Reputation: 19
For my CS class, I had to code a Stacks interface extending off of LinkedList. However, there is an error in my peek() method apparently. When I implement this into one of my other programs, I return an IndexOutOfBounds exception (Index 0; Size 0) and I cannot seem to find what exception or statement that would handle that for me in my peek() method.
public class MyStack<anyType> extends LinkedList<anyType> {
private ArrayList<anyType> list;
public MyStack() {
list = new ArrayList<anyType>(10);
}
public void push(anyType x) {
list.add(0, x);
}
public anyType pop() {
if (list.get(0) == null) {
return null;
} else {
anyType x = list.get(0);
list.remove(0);
return x;
}
}
public anyType peek() {
if (list.get(0) == null) {
return null;
} else {
anyType x = list.get(0);
return x;
}
}
public boolean isEmpty() {
if (list.size() == 0)
return true;
else
return false;
}
}
Upvotes: 0
Views: 1315
Reputation: 88
I'm assuming you're only getting this error when you have no items in your stack. If you have no items in your stack, then your stack will have no indexes and calling list.get(0) won't make sense.
You'll need to handle the case of an empty stack with no indexes:
if (list.size() == 0) return null;
Of course, this is assuming "list" itself isn't null. A much better way to do this would be to create a separate method checking a list of class invariants that include things like null references, empty stacks, etc. But for the purposes of a simple assignment this will suffice.
Upvotes: 0
Reputation: 64
Before checking if list.get(0) == null you need to check if the list even exists at that index. Use: `
if(list.size() <= 0 || list.get(0) == null)
return null
Upvotes: 3