Thursday, May 15, 2008

Stack in Java

This class extends the Vector class and represents a Last-In-First-Out (LIFO) structure of objects. It defines five new methods, which are:-

  • boolean empty()checks if the stack is empty or not
  • Object peek()only looks at the object at the top without removing that
  • Object pop()removes and returns the object at the top of the stack
  • Object push(Object item)pushes an item to the top of the stack and returns the same
  • int search(Object object)returns 1-based position of the ‘object’ in the stack

The search method returns -1, if the object is not found in the stack. The methods ‘pop’ and ‘peek’ throw EmptyStackException if they are called on an empty stack. The method ‘push’ is similar to ‘addElement’ method of the class Vector. The only difference between the two is that ‘push’ returns the same item as well whereas ‘addElement’ returns nothing. This is why the return type of ‘push’ is ‘Object’ and that of ‘addElement’ is ‘void’.


No comments: