我正在使用我之前实验室中关于链表的旧代码编写一个pop方法。我的代码看起来很完美,但我一直收到错误
错误:不兼容的类型
return top.data;
必需:AnyType
发现:对象
其中AnyType是一个类型变量:
AnyType扩展了在类堆栈中删除的Object
我不知道如何驾驭这个错误!我在其他情况下读过有关同样错误的其他帖子,但已知似乎适用于我的情况,或者我不知道如何将其应用于我的情况。
public class Stack<AnyType> implements StackInter<AnyType>
{
MyNode top = new MyNode();
public void push(AnyType x)
{
MyNode newNode = new MyNode();
newNode.data = top.data;
top.data = x;
newNode.next = top.next;
top.next = newNode;
}
public AnyType pop()
{
if(isEmpty())
return null;
else{
AnyType topStuf = top.data; // Getting error on this line
top = top.next;
return topStuff;
}
}
public boolean isEmpty()
{
return top == null;
}
public AnyType(peek)
{
return top.data;
}
}
public class MyNode<AnyType>
{
public AnyType data;
public MyNode<AnyType> next;
}
答案 0 :(得分:0)
而不是Anytype使用T. 在Java中,泛型类型默认定义为T,因为它扩展了Object Class。 并且peek函数也没有正确定义。
public T peek() {
//code here
}