To create a stack in Java, you can use the Stack
class from the java.util
package.
A stack is a last-in, first-out (LIFO) data structure that supports push and pop operations.
Here is an example of how to create a stack:
import java.util.Stack; public class Main { public static void main(String[] args) { Stack<String> stack = new Stack<>(); } }Sourcww:ew.lautturi.com
This creates a stack of type String
. You can also specify the type using the generic syntax Stack<Type>
.
To add elements to the stack, you can use the push
method. For example:
stack.push("apple"); stack.push("banana"); stack.push("cherry");
This adds the strings "apple", "banana", and "cherry" to the stack.
To remove and return the top element from the stack, you can use the pop
method. For example:
String top = stack.pop();
This removes and returns the top element, which is "cherry" in this example.
You can also use the peek
method to return the top element without removing it from the stack.