【问题标题】:get method for linked lists not working... incompatible types获取链接列表的方法不起作用...不兼容的类型
【发布时间】:2013-10-16 15:52:10
【问题描述】:

该方法应该从给定索引处的链接列表中返回“type”类型的节点。

 public type get(int index) throws Exception
    {
    int currPos = 0;
    Node<type> curr = null;

    if(start!= null && index >=0)
    {
        curr = start;
        while(currPos != index && curr != null)
        {
            curr = curr.getNext();
            currPos++;
        }
    }

    return curr;

为什么在编译时给我一个“不兼容的类型”错误?

【问题讨论】:

  • 什么是“开始”?它是在哪里定义的?
  • @CristianMeneses - 我假设start 是一个引用列表中第一个节点的字段。

标签: java list get linked-list


【解决方案1】:

您已经声明了返回type 对象的方法,但您试图返回声明为Node&lt;type&gt;curr。大概Node 类有一个getValue() 方法(或等效的方法)来检索存储在节点中的type 对象。您应该将最后一行更改为:

return curr.getValue();

更好的是,因为此时curr 可能是null

return curr == null ? null : curr.getValue();

【讨论】:

  • @MateiZera - 很高兴它成功了。在重新阅读您的代码时,我发现当到达 return 语句时,currnull 是可能的。最好把最后一行改成:return curr == null ? null : curr.getValue();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多