How to use Java Stack with Examples

java-stack-tutorial-feature-image

[no_toc]In the tutorial, Grokonez will introduce how to use Java Stack with Examples:

  • How does Java Stack work?
  • Hierarchy of Java Stack
  • Do push, pop, peek, search operations with Java Stack data structure

Related posts:
How to use Java PriorityQueue with Examples
How to use Java TreeMap with Examples

Java Stack

– Java Stack is a last-in-first-out (LIFO) data structure of objects. The usual push and pop operations are provided:

how-to-use-java-stack-data-structure-working-principle

– Java Stack extends class Vector. See a hierarchy of Java Stack:

java.lang.Object
	java.util.AbstractCollection
		java.util.AbstractList
			java.util.Vector
				java.util.Stack

how-to-use-java-stack-data-structure-hierarchy

– Java Stack has just only one Constructor:

public Stack()

-> It creates an empty Stack.

– Java Stack implements five operations that allow a Vector to be treated as a Stack:

  • public boolean empty(): check a stack is empty or not
  • public E pop(): Removes the object at the top of a stack and returns that object as the value of this function.
  • public E peek(): get the object at the top of this stack but NOT removing it from the stack.
  • public E push(E item): Pushes an item onto the top of this stack
  • public int search(Object o): Returns the 1-based position from the top of the stack where the object is located; the return value -1 indicates that the object is not on the stack.

Java Stack with Integer Elements Example

In the following example, we create an integer stack that does a list operations:

  • Create a stack
  • Push elements to stack
  • Pop elements to stack
  • Check a stack is empty or NOT
  • Look an element in a stack

-> Example Code:

import java.util.Stack;

public class JavaStackExamples {
	
	public static void main(String[] args) {
		
		Stack numbers = new Stack();
		numbers.push(8);
		numbers.push(9);
		numbers.push(1);
		numbers.push(2);
		numbers.push(5);
		numbers.push(16);

		// Get top values of the stack
		int top = numbers.peek();
		System.out.println("top's value = " + top); // 16
		
		// Get position of an element in a stack
		int position = numbers.search(5);
		System.out.println("Position of 5 is " + position); // 2
		
		// Pop each elements of numbers stack
		while(!numbers.empty()) {
			System.out.println(numbers.pop());
		}
		/*
			16
			5
			2
			1
			9
			8
		*/
		
	}
}

Java Stack with String Elements Example

import java.util.Stack;

public class JavaStackExamples {
	
	public static void main(String[] args) {
		
		Stack strings = new Stack();
		strings.push("Jack");
		strings.push("Charlie");
		strings.push("Joe");
		strings.push("George");

		// Get top values of the stack
		String top = strings.peek();
		System.out.println("top's value = " + top); // George
		
		// Get position of an element in a stack
		int position = strings.search("Charlie");
		System.out.println("Position of 'Charlie' is " + position); // 3
		
		// Pop each elements of numbers stack
		while(!strings.empty()) {
			System.out.println(strings.pop());
		}
		/*
			George
			Joe
			Charlie
			Jack
		*/
		
	}
}

Java Stack with User Defined Objects Example

– Create Developer class:

class Developer {
	Integer id;
	String name;

	public Developer(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return this.id;
	}

	public String getName() {
		return this.name;
	}

	public String toString() {
		return String.format("[id = %d, name = %s]", id, name);
	}
}

– For comparing 2 objects when using search operation of Java Stack, we need re-implement equals method:

@Override
public boolean equals(Object o) {
	if (this == o)
		return true;
	if (o == null || getClass() != o.getClass())
		return false;

	Developer developer = (Developer) o;
	return Integer.compare(developer.id, id) == 0 && Objects.equals(name, developer.name);
}

– Now create a Developer Stack, when do a list operations on it:

public class JavaStackExamples {

	public static void main(String[] args) {

		Stack devs = new Stack();
		devs.push(new Developer(1, "Jack"));
		devs.push(new Developer(4, "Joe"));
		devs.push(new Developer(10, "Davis"));
		devs.push(new Developer(6, "Mary"));

		// Get top values of the stack
		Developer top = devs.peek();
		System.out.println("top's value = " + top); // top's value = [id = 6, name = Mary] 

		// Get position of an element in a stack
		int position = devs.search(new Developer(4, "Joe"));
		System.out.println("Position of 'Joe' developer is " + position); // Position of 'Joe' developer is 3

		// Pop each elements of devs stack
		while (!devs.empty()) {
			System.out.println(devs.pop());
		}
		/*
			[id = 6, name = Mary]
			[id = 10, name = Davis]
			[id = 4, name = Joe]
			[id = 1, name = Jack]
		 */
	}
}

-> Output:

top's value = [id = 6, name = Mary]
Position of 'Joe' developer is 3
[id = 6, name = Mary]
[id = 10, name = Davis]
[id = 4, name = Joe]
[id = 1, name = Jack]

Conclusion

We had learned how to use Java Stack with examples:

  • Understand about Java Stack’s Working Principle and Hierarchy
  • Create Java Stack Examples with Integer, String and User Defined Object

Happy Learning! See you later!

Leave a Reply

Your email address will not be published. Required fields are marked *