Download Abstract Data Types in Java Abstract Data Types in Java
Transcript
In the vector implementation, the top of the stack is the element at the index Vector.size() - 1. Of course, the actual index of the top element changes with each push and pop. The fact that the Stack always works at the end of the vector instead of the beginning means that the number of times an array copy occurs is limited to the number of times the size of the underlying array must be expanded. The peek() method provides additional functionality that can be quite handy: public synchronized Object peek() Peek enables the user to view the element at the top of the stack without actually removing the item from the stack. Think of peek as a nondestructive pop. The peek operation is not strictly necessary to the stack, but it is a nice feature. The empty() method is used to determine whether the stack is empty: Public boolean empty() If the Vector.size() == 0, the stack is empty. Again, this method is not necessary to the stack but certainly is useful. The search() method is another addition to the Stack class that is not strictly necessary but is a nice feature: public synchronized int search(Object o) The method returns the distance from the top that the supplied Object is located. If the Object is not found in the stack, -1 is returned. This implementation uses the Vector.lastIndexOf() method to determine the position in the array and then subtracts that index from the number of elements in the array (vector.size()) to determine how far the element is away from the top of the stack. We also should know that, although Stack is a subclass of Vector, it provides only the default constructor. The user of the Stack class cannot specify the initial size of the underlying array or the capacity increment of the Stack (as was possible with the Vector's constructors). The default Page 129 constructor provides an initial size of 10. The default action for resizing the array is to double it each time it becomes full. Uses of the Stack The stack is used in many cases when the desired action is to access the data in the reverse order in which it was stored. This is similar to the undo function in word processing. Keystrokes and the actions caused by them can be undone by unapplying them in reverse order. Refer to the example in Chapter 1 of the mechanism used to pass arguments to a method when it is called. The calling method first pushes its current instruction address onto the stack, and then the arguments are pushed onto the stack. After program control is passed to the method, the arguments are popped back off the stack. And, finally, when the method is ready to return, it