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

前端 未结 4 1967
心在旅途
心在旅途 2021-01-14 15:57

Here is my code:

package datastructures;

import java.util.Iterator;

public class Stack{
    private class Node{
        T data;
        N         


        
相关标签:
4条回答
  • 2021-01-14 16:47

    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.

    0 讨论(0)
  • 2021-01-14 16:49

    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
    
    0 讨论(0)
  • 2021-01-14 16:57

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

    0 讨论(0)
  • 2021-01-14 17:02

    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)

    0 讨论(0)
提交回复
热议问题