incompatible types object cannot be converted to t where t is a type variable

I'm getting the Incompatible types: Object cannot be converted to T where T is a type variable: T extends Object declared in class Stack.
Can you please help, I don't know why it is so, method pop() and getData() are of the same type T...
Here is the shortened code.

public class Stack<T> {
    Node head;

    public T pop() {
         return head.getData();    //the error is on this line
    }

    private class Node <T> {
        private final T data;
        private Node next;

        private Node(T data, Node next) {
            this.data=data;
            this.next=next;
        }

        private T getData() {
            return data;
        } 
    }
}

Upvotes: 1

Views: 17777

Answers (2)

rgettman
rgettman

Reputation: 178263

You've declared an inner class Node that defines its own type parameter T (it's different than Stack's T). However, you are using a raw Node when you declare head. Type erasure applies, and calling getData() on a raw Node returns an Object.

Remove the type parameter T on Node. Because it's not static, the Stack's class's T type parameter is in scope for Node. Node can simply use Stack's T type parameter.

private class Node  {

Upvotes: 3

Petar Minchev
Petar Minchev

Reputation: 47373

It must be Node<T> head. You forgot to add the type parameter.

Upvotes: 5

Related Questions