Your code in "push" takes two arguments: An integer representing the index you're "pushing" the item onto, and the item that you want to push onto the stack. You got the Exception because you tried to push an item onto the stack at index = 3, but the array is too small; therefore, you can't push anything onto index 3 since it doesn't have 3 indexes.
Why do you need to give the 'push' method an index, anyway? Instead, you could have a variable 'currentSize' in the MStack class that keeps track of how large your stack is. Then, in your push() method, you'd just automatically add the new item onto the end and increment the 'currentSize' variable.
A possible problem: Since you are using an array, and not an Arraylist, you need to make sure that you allocate enough space (make the array big enough) to begin with. Otherwise, at some point, you might get an ArrayIndexOutOfBoundsException. If your array reaches it's maximum size (or at some point before it reaches its max size), you will have to make a new array which has a bigger size and copy the old one over to it. So somehow you're either not making your array big enough or you're calculating the wrong index (that you pass to the push method).
Last edited by BestJewSinceJC; Jan 13th, 2009 at 4:22 pm.
Reputation Points: 874
Solved Threads: 352
Posting Maven
Offline 2,758 posts
since Sep 2008