Good code is its own best documentation. As you are about to add a comment, ask yourself, How can I improve the code so that this comment isn't needed? Improve the code and then document it to make it even clearer. Steve McConnell

Stack

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

0 Comments


Definition

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

Character

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)
			   st.push(i);
		      
		   System.out.println("Removed element "+st.pop() +" from Stack");
		      
		   System.out.println("Elements after remove: "+st);
	}

}
						

Output

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

Comparison

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.

0 Comments



Please login to add comments.