关于equals和compareto方法的java问题

ss2ws0br  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(297)

嗨,我对java非常陌生,有两个方法在linkedlist上运行时遇到了这个问题。
我编写的find函数总是返回false。find方法是将一个type e元素作为参数,如果该项在链表中,则返回true,否则返回false。
max方法是,如果列表不为空,则返回列表中的最大元素(在本例中是最长的字符串),如果列表为空,则返回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;
  }
9o685dep

9o685dep1#

你的 find 总是返回false,因为初始化 node 以及 current 设置为null,因此从不进入循环。此外,您应该将e与项进行比较,而不是与节点进行比较。
可能是:

public boolean find(E e){
    Node current = head;
    while (current != null){
        if (current.item.equals(e)){

相关问题