Here is my code:
package datastructures;
import java.util.Iterator;
public class Stack<T>{
private class Node<T>{
T data;
Node next;
}
private int size;
private Node head;
private Node newNode(T data){
Node new_node = new Node();
new_node.data = data;
new_node.next = null;
return new_node;
}
public Stack(){
size = 0;
head = null;
}
public T pop() {
if(head == null)
return null;
T ret_val = head.data; //Error here
head = head.next;
this.size--;
return ret_val;
}
}
I get the error in the pop method, here is the error:
Error: incompatible types : java.lang.Object cannot be converted to T
I don't understand this error, I'm not using Object anywhere in my code.
When you declare Node as
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
Just use
You are declaring
Node
inner type with its own type parameter, soT
ofNode
shadowsT
ofStack
, and they are essentially different types.Remove declaration of type parameter
<T>
in yourNode
type (that's probably what you mean for it)Node's data field doesn't know it's type.
Try giving the type when you initialize head.
Now, new_node knows that the data field is of type T.
(For Java 8) You can use a typed variable with the diamond operator:
Otherwise the generic is initalized as
Object
and therefore the error is shown.