error: incompatible types AnyType topStuff = top.data;
error: incompatible types AnyType topStuff = top.data;
我正在使用之前关于链表的实验中的旧代码编写 pop 方法。我的代码看起来很完美,但我总是收到错误
error: incompatible types
return top.data;
required: AnyType
found: Object
where AnyType is a type-variable:
AnyType extends Object decleared in class stack
我不知道如何解决这个错误!我在其他情况下阅读过有关此相同错误的其他帖子,但已知似乎适用于我的情况,或者我不知道如何将其应用到我的情况。
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;
}
使用 T 而不是 Anytype。
在 Java 中,泛型类型默认定义为 T,因为它扩展了 Object Class。
而且 peek 函数定义不正确。
public T peek() {
//code here
}
我正在使用之前关于链表的实验中的旧代码编写 pop 方法。我的代码看起来很完美,但我总是收到错误
error: incompatible types
return top.data;
required: AnyType
found: Object
where AnyType is a type-variable:
AnyType extends Object decleared in class stack
我不知道如何解决这个错误!我在其他情况下阅读过有关此相同错误的其他帖子,但已知似乎适用于我的情况,或者我不知道如何将其应用到我的情况。
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;
}
使用 T 而不是 Anytype。 在 Java 中,泛型类型默认定义为 T,因为它扩展了 Object Class。 而且 peek 函数定义不正确。
public T peek() {
//code here
}