如何制作链接栈泛型?

时间:2018-11-28 07:52:04

标签: java generics

我正在做实验,我查看了很多Java泛型示例,但我听不懂。我的目标是实现链接堆栈。它有2个文件:IntStack.javaIntNode.java。这些代码的一部分是:

public class IntNode {
    private int element = 0;
    private IntNode next = null;
    public IntNode(final int data, final IntNode next) {
        this.element = data;
        this.next = next;
}

public class IntStack {
private IntNode top = null;
public boolean isEmpty() {
    return this.top == null;
}

如何将它们转换为泛型类型?我知道它应该使用<T>,并且我写这些代码,对与错?

public class Node<T> {
    private T element;
    private Node<T> next = null;
    public Node(final T data,final Node next) {
        this.element = data;
        this.next = next;
    }
}

1 个答案:

答案 0 :(得分:1)

您很近。 Node构造函数的Node参数也应参数化:

public class Node<T> {   
    private T element;
    private Node<T> next = null;
    public Node(final T data,final Node<T> next) {
        this.element = data;
        this.next = next;
    }
}