【问题标题】:compareTo: how to return a boolean?compareTo:如何返回布尔值?
【发布时间】:2012-05-02 04:10:41
【问题描述】:

我被告知 compareTo 必须返回一个 int...而不是 Boolean。
例如:

返回

0 如果 b 相等
-1 如果 a +1 如果 a > b

我对此有点困惑。任何帮助将不胜感激。

public int compareTo(Cheese anotherCheese)
   throws ClassCastException
   {
       if (!(anotherCheese instanceof Cheese))
            throw new ClassCastException("A Cheese object expected.");

       if(getCheeseType().compareTo(anotherCheese.getCheeseType()))
            return -1;
       else if (getCheeseType().compareTo(anotherCheese.getCheeseType()))
            return 1;
       else
            return cheesePrice > anotherCheese.getCheesePrice();
   }   

当我编译时,我收到错误消息:


类型不兼容
if(getCheeseType().compareTo(anotherCheese.getCheeseType()))
类型不兼容
else if (getCheeseType().compareTo(anotherCheese.getCheeseType()))
不兼容的类型
return cheesePrice > anotherCheese.getCheesePrice();

【问题讨论】:

    标签: java


    【解决方案1】:

    compareTo 确实返回int,而不是boolean。因此,您会收到那些编译错误。在if 语句中,您必须放入boolean

    所以不是

    if(getCheeseType().compareTo(anotherCheese.getCheeseType()))

    if(getCheeseType().compareTo(anotherCheese.getCheeseType()) < 0)

    【讨论】:

      【解决方案2】:

      只是做

      return getCheeseType().compareTo(anotherCheese.getCheeseType());
      

      如果你也想按价格比较,那么做

      if(getCheeseType().compareTo(anotherCheese.getCheeseType())!=0)
          return getCheeseType().compareTo(anotherCheese.getCheeseType());
      //cheeseTypes are equal
      if(cheesePrice < anotherCheese.getCheesePrice())
          return -1;
      else if (cheesePrice > anotherCheese.getCheesePrice())
          return 1;
      else
          return 0;
      

      【讨论】:

        【解决方案3】:
           // Order by type.
           int delta = getCheeseType().compareTo(anotherCheese.getCheeseType());
           if (delta != 0) { return delta; }
           // If of the same type, order by price.
           if (cheesePrice < anotherCheese.getCheesePrice()) { return -1; }
           if (cheesePrice > anotherCheese.getCheesePrice()) { return 1; }
           return 0;
        

        【讨论】:

          【解决方案4】:

          是的 compareTo 方法将返回 int 类型,而不是 boolean。但是您在 if 循环中使用了getCheeseType().compareTo(anotherCheese.getCheeseType()),这将导致编译时错误。改成这样。

          public int compareTo(Cheese anotherCheese)
             throws ClassCastException
             {
                 if (!(anotherCheese instanceof Cheese))
                      throw new ClassCastException("A Cheese object expected.");
          
                 else return getCheeseType().compareTo(anotherCheese.getCheeseType()))
          
             }   
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-04-07
            • 2013-08-18
            • 2013-05-21
            • 2011-12-14
            • 2020-07-29
            • 2014-12-13
            • 1970-01-01
            相关资源
            最近更新 更多