Idea Analysis: Since you use generics to implement the stack structure, you cannot use the stack package that comes with JDK. You need to define a stack structure yourself, such as LinkedList.
The code is as follows:
Stack.java:
The code copy is as follows:
package cn.edu.xidian.crytoll;
import java.util.LinkedList;
public class Stack<T> {
private LinkedList<T> container = new LinkedList<T>();
public void push(T t) {
container.addFirst(t);
}
public T pop() {
return container.removeFirst();
}
public boolean empty() {
return container.isEmpty();
}
}
StackTest.java:
The code copy is as follows:
package cn.edu.xidian.crytoll;
public class StackTest {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Add string to the stack:");
System.out.println("Java for video");
System.out.println("Detailed Java");
System.out.println("Java from Beginner to Mastery (2nd Edition)");
stack.push("Video Learn Java"); //Add strings to the stack
stack.push("Details Java"); //Add strings to the stack
stack.push("Java from Beginner to Mastery (2nd Edition)"); //Add strings to the stack
System.out.println("Fetch string from stack:");
while (!stack.empty()) {
System.out.println((String) stack.pop());//Delete all elements in the stack and output
}
}
}