Here is my code:
package datastructures;
import java.util.Iterator;
public class Stack{
private class Node{
T data;
N
Node's data field doesn't know it's type.
Try giving the type when you initialize head.
private Node<T> head;
private Node<T> newNode(T data){
Node new_node = new Node<T>();
new_node.data = data;
new_node.next = null;
return new_node;
}
Now, new_node knows that the data field is of type T.
When you declare Node as
private class Node<T>
you're declaring a generic type with another T as the T in the enclosing type. You're hiding T. So, in short, it's as if you were declaring it as
private class Node<E>
Just use
private class Node
(For Java 8) You can use a typed variable with the diamond operator:
private Node newNode(T data) {
Node<T> new_node = new Node<>();
new_node.data = data;
new_node.next = null;
return new_node;
}
Otherwise the generic is initalized as Object
and therefore the error is shown.
You are declaring Node
inner type with its own type parameter, so T
of Node
shadows T
of Stack
, and they are essentially different types.
Remove declaration of type parameter <T>
in your Node
type (that's probably what you mean for it)