This content originally appeared on DEV Community and was authored by Jack Pritom Soren
The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to store the collection of objects.
The stack data structure has the two most important operations that are push and pop. The push operation inserts an element into the stack and pop operation removes an element from the top of the stack.
Java Stack Example :
Example 1 :
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("jack");
stack.push("john");
stack.push("jacob");
System.out.println("Before Pop");
System.out.println(stack);
stack.pop();
System.out.println("After Pop");
System.out.println(stack);
Example 2 :
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Length:");
int number = scanner.nextInt();
scanner.nextLine();
for (int i= 1;i<=number;i++)
{
stack.push(scanner.nextLine());
}
System.out.println("Before Pop");
System.out.println(stack);
System.out.println("Pop Count:");
int popNumber = scanner.nextInt();
scanner.nextLine();
for (int i=1;i<=popNumber; i++)
{
stack.pop();
}
System.out.println(stack);
}
}
This content originally appeared on DEV Community and was authored by Jack Pritom Soren
Jack Pritom Soren | Sciencx (2022-03-17T19:02:14+00:00) Stack (Java Collections). Retrieved from https://www.scien.cx/2022/03/17/stack-java-collections/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.