不兼容的类型在Java中初始化泛型类型的堆栈

Gia*_*omo 3 java generics stack compiler-errors java-8

我试图在Java上编写一个Stack结构.我的代码如下:

class Stack<T>{
  private static class Node<T>{
    private T data;
    private Node<T> next;

    public Node(T data){
      this.data = data;
    }
  }
  private Node<T> top;

  public Stack(){
    top = null;
  }
  public Stack(Node<T> top){
    this.top = top;
  }

  public static void main(String []args){
    Node<Integer> stackNode = new Node<Integer>(1);
    Stack<Node<Integer>> myStack = new Stack<Node<Integer>>(stackNode);
  }
}
Run Code Online (Sandbox Code Playgroud)

在main方法中,我首先使用Integer 1初始化一个名为stackNode的节点,这样可行.然后我尝试做的是使用stackNode作为顶级节点初始化我的Stack.这不起作用,当我编译我得到错误:

    Stack.java:56: error: incompatible types: Node<Integer> cannot be converted to Node<Node<Integer>>
        Stack<Node<Integer>> myStack = new Stack<Node<Integer>>(stackNode);
Note: Some messages have been simplified; recompile with
    -Xdiags:verbose to get full output 1 error
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 5

StackNode应具有相同的类型:

Node<Integer> stackNode = new Node<Integer>(1);
Stack<Integer> myStack = new Stack<Integer>(stackNode);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,使用<>Java 7中引入的语法可以稍微清理一下代码:

Node<Integer> stackNode = new Node<>(1);
Stack<Integer> myStack = new Stack<>(stackNode);
Run Code Online (Sandbox Code Playgroud)