2012-05-01 129 views
1

我被告知compareTo必須返回一個int ...不是布爾值。
例如:
compareTo:如何返回一個布爾值?

返回

0如果一個等於b
-1,如果一個< b
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();

回答

4

compareTo確實返回int,而不是boolean。因爲這個,你會得到那些編譯錯誤。在if聲明中,您必須輸入boolean

所以不是

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

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

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

    }