您好我是Java的新手,并且在使用linkList的2个方法时遇到了这个问题。
我写的find函数总是返回false。 find方法是将类型E元素作为参数,如果项目在链接列表中,则返回true,否则返回false。
max方法是在列表不为空时返回列表中的最大元素(本例中为Longest String),如果为空列表则返回null。必须通过compareTo()进行比较。 我写的最大值只是查看每个元素的第一个字母(字符串)。
非常感谢任何帮助!
public boolean find(E e){
LinkedListTest<E>.Node node = null;
Node current =node;
while (current != null){
if (current.equals(e)){
return true;
}
else{
current=current.next;
}
}
return 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;
}
答案 0 :(得分:3)
您的find
始终返回false,因为您将node
和current
初始化为null,因此永远不会输入循环。此外,您应该将e与项目进行比较,而不是与节点进行比较。
应该是:
public boolean find(E e){
Node current = head;
while (current != null){
if (current.item.equals(e)){