Software is like sex: Itís better when itís free. Linus Torvalds


Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 20:12:37



The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends Vector class.


The stack is a subclass of Vector that implements a standard last-in, first out stack.
The initial stack does not contain any element.
Stack provide pop, push and peek operations.
Java uses an array based implementation Stack.

source Code

package com.careerdrill.collections.list;

import java.util.Arrays;
import java.util.Stack;

public class StackUse {

	public static void main(String[] args) {

			Integer []array={11,22,33,44,55};
		   Stack< Integer > st = new Stack< Integer >();
		   System.out.println("Push the elements to the stack: "+ Arrays.toString(array));
		   for(Integer i : array)
		   System.out.println("Removed element "+st.pop() +" from Stack");
		   System.out.println("Elements after remove: "+st);



Push the elements to the stack: [11, 22, 33, 44, 55]
Removed element 55 from Stack
Elements after remove: [11, 22, 33, 44]


Stack ArrayDeque
Stack is vector-based implementation. ArrayDeque is the array-based implementation.
Push and pop the elements to the stack gives in constant time. addFirst and removeFirst operations in constant time.
items are added to and removed from the top of the stack. Uses double ended queue.
Support Stack notation. deque extends the notion of a queue.
Stack has no interface. Dequeue is an interface and implemented in ArrayDequeue.

When to use

If you want use simple stack, you can use stack class.


Please login to add comments.