
What is Java Stack and how to implement Java Stack without using any Collection or Utilities? Here is a tutorial which we published some time back.
In this tutorial we will go over steps on How to implement Java Stack using Collection or Utility?
Let’s get started:
- Create java class CrunchifyJavaStackUsingCollection.java
- Copy below code in to your Eclipse or IntelliJ IDEA class
package crunchify.com.java.tutorials;
import java.util.Stack;
/**
* @author Crunchify.com
* How to implement Stack in Java using Collection?
* Revision: 1.1
*/
public class CrunchifyJavaStackUsingCollection {
public static void main(String[] crunchifyArgs) {
// Stack: The Stack class represents a last-in-first-out (LIFO) stack of objects.
// It extends class Vector with five operations that allow a vector to be treated as a stack.
// The usual push and pop operations are provided, as well as a method to peek at the top item on the stack,
// a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.
// When a stack is first created, it contains no items.
Stack<Integer> crunchifyStack = new Stack<Integer>();
// push(): Pushes an item onto the top of this stack.
crunchifyStack.push(111);
crunchifyStack.push(444);
crunchifyPrint("The crunchifyStack size is " + crunchifyStack.size());
// pop(): Removes the object at the top of this stack and returns that object as the value of this function.
crunchifyStack.pop();
crunchifyStack.push(777);
// peek(): Looks at the object at the top of this stack without removing it from the stack.
crunchifyPrint("The top element of crunchifyStack is " + crunchifyStack.peek());
// size(): Returns the number of components in this vector.
crunchifyPrint("The crunchifyStack size is " + crunchifyStack.size());
crunchifyStack.pop();
if (crunchifyStack.isEmpty()) {
crunchifyPrint("The crunchifyStack is empty");
} else {
crunchifyPrint("The crunchifyStack is not empty");
}
}
// Simple Crunchify Print Utility
private static void crunchifyPrint(Object crunchifyValue) {
System.out.println(crunchifyValue);
}
}
Run Java Application
Just run above Program as Java Application and you should see result as below.
The crunchifyStack size is 2 The top element of crunchifyStack is 777 The crunchifyStack size is 2 The crunchifyStack is not empty Process finished with exit code 0
Let me know if you see any issue running above program.
The post How to implement Stack in Java using Collection? appeared first on Crunchify.
0 Commentaires