不兼容的类型对象无法转换为 t,其中 t 是类型变量
incompatible types object cannot be converted to t where t is a type variable
我得到 不兼容的类型:对象无法转换为 T,其中 T 是类型变量:T 扩展了 class 堆栈中声明的对象。
能不能帮帮忙,我不知道为什么会这样,方法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;
}
}
}
必须是Node<T> head
。您忘记添加类型参数。
您已经声明了一个内部 class Node
,它定义了自己的类型参数 T
(它不同于 Stack
的 T
)。但是,当您声明 head
时,您使用的是原始 Node
。应用类型擦除,并在原始 Node
returns 和 Object
.
上调用 getData()
删除 Node
上的类型参数 T
。因为它不是 static
,Stack
的 class 的 T
类型参数在 Node
的范围内。 Node
可以简单地使用 Stack
的 T
类型参数。
private class Node {
我得到 不兼容的类型:对象无法转换为 T,其中 T 是类型变量:T 扩展了 class 堆栈中声明的对象。
能不能帮帮忙,我不知道为什么会这样,方法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;
}
}
}
必须是Node<T> head
。您忘记添加类型参数。
您已经声明了一个内部 class Node
,它定义了自己的类型参数 T
(它不同于 Stack
的 T
)。但是,当您声明 head
时,您使用的是原始 Node
。应用类型擦除,并在原始 Node
returns 和 Object
.
getData()
删除 Node
上的类型参数 T
。因为它不是 static
,Stack
的 class 的 T
类型参数在 Node
的范围内。 Node
可以简单地使用 Stack
的 T
类型参数。
private class Node {