[英]get method for linked lists not working… incompatible types
The method is supposed to return a node of type "type" from a link list at a given index. 该方法应该从给定索引处的链接列表返回类型“类型”的节点。
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;
why is it giving me an "incompatible types" error at compile time ? 为什么它在编译时给我一个“不兼容的类型”错误?
You've declared the method to return a type
object, but you're trying to return curr
which is declared as Node<type>
. 您已声明该方法返回一个
type
对象,但您正在尝试返回声明为Node<type>
curr
。 Presumably class Node
has a getValue()
method (or something equivalent) to retrieve the type
object stored in the node. 推测类
Node
有一个getValue()
方法(或类似的东西)来检索存储在节点中的type
对象。 You should change the last line to: 您应该将最后一行更改为:
return curr.getValue();
Better yet, since it is possible for curr
to be null
at that point: 更好的是,因为当时
curr
可能为null
:
return curr == null ? null : curr.getValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.