嗨,我是Java的新手,但链表有此问题。我的find和max方法无法产生正确的输出。
find方法将使用类型E元素作为参数,如果该项在链接的List中,则返回true,否则返回false。
如果列表不为空,则max方法将返回列表中的最大元素;如果为空,则返回null。比较必须通过compareTo()完成。
我尝试查找确实在列表中的“ Apple”,但是返回false。
同样,我得到的最大元素是“苹果”,而不是“西瓜”。
任何帮助是极大的赞赏!
public E max(){
Iterator<E> iterator=iterator();
E max = iterator.next();
while (iterator.hasNext())
{
E next = iterator.next();
if (max.compareTo(next) > 0)
max = next;
}
return max;
}
最佳答案
if (current.equals(e)){
return true;
您需要比较节点的项目,而不是节点本身。
if (max.compareTo(next) > 0)
max = next;
这种比较需要颠倒:如果旧的
max
小于当前项目,则找到了新的。