Home > Java > javaTutorial > body text

Java uses generics to implement stack structure example sharing

高洛峰
Release: 2017-01-18 11:14:01
Original
1389 people have browsed it

Idea analysis: Since the stack structure is implemented using generics, you cannot use the stack package that comes with the JDK. You need to define a stack structure yourself, 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();
    }
}
Copy after login

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("向栈中增加字符串:");
        System.out.println("视频学Java");
        System.out.println("细说Java");
        System.out.println("Java从入门到精通(第2版)");
        stack.push("视频学Java");  //向栈中增加字符串
        stack.push("细说Java");   //向栈中增加字符串
        stack.push("Java从入门到精通(第2版)"); //向栈中增加字符串
        System.out.println("从栈中取出字符串:");
        while (!stack.empty()) {
            System.out.println((String) stack.pop());//删除栈中全部元素并进行输出
        }
    }
}
Copy after login

More Java uses generics to implement stack structure examples to share related articles Please pay attention to PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template