简体   繁体   中英

incompatible types : java.lang.Object cannot be converted to T

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

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

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 .

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)

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM