Reputation: 571
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
Upvotes: 3
Views: 300
Reputation: 54148
You use Stack<Node<Integer>>
and Stack<T>
which makes T=Node<Integer>
, but in the constructor you have Node<T>
so it would require a Node<Node<Integer>>
and you give a Node<Integer>
You need to set same for both (and may use <>
(diamond operator) for clarity) :
Node<Integer> stackNode = new Node<>(1);
Stack<Integer> myStack = new Stack<>(stackNode);
Upvotes: 3
Reputation: 311188
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);
Upvotes: 5