Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incompatible types initializing stacks of generic types in Java

I am trying to program a Stack structure on Java. My code looks as follows:

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);
  }
}

in the main method, I first initialize a node called stackNode with the Integer 1, this works. What I then try to do, is initializing my Stack with the stackNode as top node. This is not working, when I compile I get the error:

    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
like image 630
Giacomo Avatar asked Jun 11 '26 23:06

Giacomo


1 Answers

The Stack and the Node should have the same type:

Node<Integer> stackNode = new Node<Integer>(1);
Stack<Integer> myStack = new Stack<Integer>(stackNode);

BTW, using the <> syntax introduced in Java 7 could clean up the code a bit:

Node<Integer> stackNode = new Node<>(1);
Stack<Integer> myStack = new Stack<>(stackNode);
like image 61
Mureinik Avatar answered Jun 14 '26 16:06

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!