A Stack is a data structure where you add elements to the “top” of the stack, and also remove elements from the top again. This is also referred to as the “Last In First Out (LIFO)” principle. Here is a Stack usage example:

Stack stack = new Stack();

stack.push("1");
stack.push("2");
stack.push("3");

// Look at top object (“3”), without taking it off the stack.
Object objTop = stack.peek();

The push() method pushes an object onto the top of the Stack.

The peek() method returns the object at the top of the Stack, but leaves the object on of the Stack.

The pop() method returns the object at the top of the stack, and removes the object from the Stack.

 


Searching the Stack
You can search for an object on the stack to get it’s index, using the search() method. Here is how you search a Stack for an object:

Stack stack = new Stack();

stack.push("1");
stack.push("2");
stack.push("3");

int index = stack.search("3"); //index = 1


Some methods :-

  • isEmpty()
    Tests if this vector has no components.
  • iterator()
    Returns an iterator over the elements in this list in proper sequence.
  • remove(int index)
    Removes the element at the specified position in this Vector.
  • size()
    Returns the number of components in this vector.
  • clear()
    Removes all of the elements from this Vector. The Vector will be empty after this call returns.
  • E peek()
    Looks at the object at the top of this stack without removing it from the stack.
  • E pop()
    Removes the object at the top of this stack and returns that object as the value of this function.
  • E push(E item)
    Pushes an item onto the top of this stack.
  • contains(Object o)
    Returns true if this vector contains the specified element.
  • get(int index)
    Returns the element at the specified position in this Vector.
  • indexOf(Object o)
    Returns the index of the first occurrence of the specified element in this vector