【问题标题】:error: incompatible types AnyType topStuff = top.data;错误:不兼容的类型 AnyType topStuff = top.data;
【发布时间】:2015-10-02 13:55:36
【问题描述】:

我正在使用我以前实验室中关于链表的旧代码编写一个 pop 方法。我的代码看起来很完美,但我不断收到错误

错误:类型不兼容
返回 top.data;
必需:AnyType
找到:对象
其中 AnyType 是一个类型变量:
AnyType 扩展了在类堆栈中清除的对象

我不知道如何解决这个错误!我在其他情况下阅读了有关此相同错误的其他帖子,但已知似乎适用于我的情况,或者我不知道如何将其应用于我的情况。

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;
}

【问题讨论】:

    标签: linked-list stack


    【解决方案1】:

    使用 T 代替 Anytype。 在 Java 中,泛型类型默认定义为 T,因为它扩展了 Object Class。 而且 peek 函数定义不正确。

    public T peek() {
        //code here  
    }
    

    【讨论】:

    • 我应该将所有 AnyType 声明更改为 T 还是仅更改方法声明?
    • 感谢您的帮助!我最终将 top.data 转换为类型“T”
    • 只使用了 T 我认为只是参考 javase 文档以了解泛型编程中的实现细节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2012-10-19
    相关资源
    最近更新 更多