【问题标题】:Java questions on equals and compareTo method关于 equals 和 compareTo 方法的 Java 问题
【发布时间】:2015-04-28 05:06:55
【问题描述】:

您好,我是 Java 新手,在linkedList 上运行 2 种方法时遇到了这个问题。

我写的 find 函数总是返回 false。 find 方法是将类型 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;
  }

【问题讨论】:

    标签: java linked-list equals compareto


    【解决方案1】:

    您的find 总是返回false,因为您将nodecurrent 初始化为null,因此永远不会进入循环。此外,您应该将 e 与 item 进行比较,而不是与 Node 进行比较。

    应该是这样的:

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

    【讨论】:

    • 您好,感谢您的回复!调用该函数时,我将其视为字符串是否正确? System.out.println(lst.find("芒果"));因为我关心的是,参数是E,但我调用字符串“Mango”。
    • @Robert 是的,你是对的,因为你创建了一个LinkedListTest&lt;String&gt;,所以在这种情况下 E 是字符串。
    • 感谢您的帮助!我仍然对 max 函数感到困惑。
    • @Robert 我在您的 max 方法中看到的唯一问题是,如果列表为空,它将引发异常,因为您在检查 hasNext() 之前调用了第一个 next()。你得到什么作为 max 的输出?你应该得到李子。你还期待别的吗?
    • 我的意思是找到最长的字符串元素,它应该返回橙色。所以我想我使用 compareTo 是错误的?因为它是按字典顺序完成的。关于如何找到最长的字符串元素有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2011-10-10
    相关资源
    最近更新 更多