Java Collections – Stack Example
A Stack is a type of collection in which the operations of adding elements into the collection is known as push, and removal of the elements from the collection is known as pop. When an element is pushed onto the stack previous elements are push down further. Any removal of the elements using pop, removes the very last element from the top of the stack. This data structure is referred to as LIFO (Last-In-First-Out). In Java, the Stack class extends the Vector class and adds five operations.
Worthy Note
You should consider using the Deque class as it provides a more complete and consistent set of LIFO operations than the Stack class.
Creating a Stack
Stack<String> myStack = new Stack<String>();
Stack Operations
- push(obj): adds an item onto the top of the stack
- pop(): removes an item from the stop of the stack
- peek(): return the item at the top without removing it from the stack
- size(): returns the number of elements in the stack
- isEmpty(): checks whether the stack has no elements
- search(obj): returns the distance from the top where element exists
Adding elements (Pushing)
Adding elements to myStack is done by using the push(Object obj) method. This will add an item to the top of the stack.
myStack.push("Hello");
Removing elements (Popping)
Removing elements is just a matter of calling the method pop(). This will remove an item from the top of the stack.
myStack.pop();
Size of Collection
Returning the number of elements in a Stack is as easy as calling the size() method.
myStack.size();
Iterating through the Collection
Creating an iterator and looping through the collection is quite easy and straight forward.
// Loop through the collection of cars using iterator ListIteratoriter = myStack.listIterator(); while (iter.hasNext()) { String words = iter.next(); System.out.println(words); }
Full Program Listing
package com.avaldes.tutorials; import java.util.Iterator; import java.util.Stack; import java.util.StringTokenizer; public class StackExample { public static void main(String[] args) { Stack<String> myStack = new Stack<String>(); String phrase = "In the end, it's not the years in your life that count. It's the life in your years - Abraham Lincoln"; System.out.println("Reversing a Phrase using a Stack"); System.out.println(phrase); System.out.println("Size of myStack is now " + myStack.size()); System.out.println("Tokenizing and pushing all the words onto the Stack"); // Split all the words and push them down into the stack StringTokenizer words = new StringTokenizer(phrase); while (words.hasMoreTokens()) { myStack.push(words.nextToken()); } // Show all the words in the stack {in correct order} System.out.println(myStack); System.out.println("Size of myStack is now " + myStack.size()); System.out.println("Popping all of the words out of the Stack..."); int size = myStack.size(); // Now pop all the words out of the stack, resulting in reverse order System.out.print("["); for (int i=0; i < size; i++) { String word = myStack.pop(); System.out.print(word); if (i<size-1) System.out.print(", "); } System.out.println("]"); } }
Output
Reversing a Phrase using a Stack In the end, it's not the years in your life that count. It's the life in your years - Abraham Lincoln Size of myStack is now 0 Tokenizing and pushing all the words onto the Stack... [In, the, end,, it's, not, the, years, in, your, life, that, count., It's, the, life, in, your, years, -, Abraham, Lincoln] Size of myStack is now 21 Popping all of the words out of the Stack... [Lincoln, Abraham, -, years, your, in, life, the, It's, count., that, life, your, in, years, the, not, it's, end,, the, In]
Other Related Posts
Map Examples
- Hashtable Example
Simple example shows you step by step how to use Hashtable - HashMap Example
Simple example shows you step by step how to use HashMap - TreeMap Example
Simple example shows you step by step how to use TreeMap to sort a collection - EnumMap Example
Simple example shows you step by step how to use EnumMap for type-safety and speed of finite list of elements - WeakHashMap Example
Simple example shows you step by step how to use WeakHashMap - LinkedHashMap Example
Simple example shows you step by step how to use LinkedHashMap - Performance Comparison HashMap vs Hashtable vs TreeMap
Performance Comparison - Performance Comparison HashMap vs Hashtable vs TreeMap Benchmark Test
List Examples
- Stack Example
Simple example shows you step by step how to use Stack - Vector Example
Simple example shows you step by step how to use Vector - LinkedList Example
Simple example shows you step by step how to use LinkedList - ArrayList Example
Simple example shows you step by step how to use ArrayList - Performance Comparison between the four list implementations
Performance Comparison of ArrayList, LinkedList, Vector, and Stack - Performance Comparison ArrayList vs LinkedList
Performance Comparison - ArrayList vs LinkedList
Set Examples
- BitSet Example
Simple example shows you step by step how to use BitSet - EnumSet Example
Simple example shows you step by step how to use EnumSet - HashSet Example
Simple example shows you step by step how to use HashSet - TreeSet Example
Simple example shows you step by step how to use TreeSet - LinkedHashSet Example
Simple example shows you step by step how to use LinkedHashSet
Leave a Reply