compareTo:如何返回布尔值?

时间:2012-05-01 20:02:45

标签: java

我被告知compareTo必须返回一个int ...而不是布尔值 例如:

返回

如果等于b,则

0 -1如果< b
如果a> +1,则+1 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();

4 个答案:

答案 0 :(得分:4)

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

所以而不是

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

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

答案 1 :(得分:0)

只是做

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;

答案 2 :(得分:0)

   // 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;

答案 3 :(得分:0)

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()))

   }