java 不兼容的类型对象无法转换为 t,其中 t 是类型变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29309727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
incompatible types object cannot be converted to t where t is a type variable
提问by Filoména Petr?lénová
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.
我得到了不兼容的类型:对象无法转换为 T,其中 T 是类型变量:T 扩展了类 Stack 中声明的对象。
你能帮忙吗,我不知道为什么会这样,方法 pop() 和 getData() 是相同的类型 T ...
这是缩短的代码。
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;
}
}
}
回答by Petar Minchev
It must be Node<T> head
. You forgot to add the type parameter.
必须是Node<T> head
。您忘记添加类型参数。
回答by rgettman
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
.
您已经声明了一个内部类Node
,该类定义了自己的类型参数T
(它与Stack
's不同T
)。但是,您Node
在声明head
. 类型擦除适用,并调用getData()
原始Node
返回一个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.
删除类型参数T
上Node
。因为它不是static
,所以Stack
类的T
类型参数在 的范围内Node
。 Node
可以简单地使用Stack
的T
类型参数。
private class Node {