Java USES generics to implement stack structure example sharing

  • 2020-04-01 03:06:28
  • OfStack

Analysis: since you're implementing the stack structure with generics, you can't use the stack package that comes with the JDK. You need to define your own stack structure, such as LinkedList.

The code is as follows:

Stack. Java:


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:


package cn.edu.xidian.crytoll;

public class StackTest {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        System.out.println("Adds a string to the stack : ");
        System.out.println(" Video to learn Java");
        System.out.println(" In detail Java");
        System.out.println("Java From introduction to mastery ( The first 2 version )");
        stack.push(" Video to learn Java");  //Adds a string to the stack
        stack.push(" In detail Java");   //Adds a string to the stack
        stack.push("Java From introduction to mastery ( The first 2 version )"); //Adds a string to the stack
        System.out.println(" Extract a string from the stack: ");
        while (!stack.empty()) {
            System.out.println((String) stack.pop());//Deletes all elements in the stack and outputs them
        }
    }
}


Related articles: