2012-10-24 17 views
3

我跟着一個教程,但未能爲我的BST我的CountryComparable製作您自己的課程「可比較」

主要:

BinarySearchTree A = new BinarySearchTree(); 
Country a = new Country("Romania", "Bucharest", 1112); 
A.insert(a); 

國家類:

public int compareTo(Object anotherCountry) throws ClassCastException { 
    if (!(anotherCountry instanceof Country)) 
     throw new ClassCastException("A Country object expected."); 
    String anotherCountryName = ((Country) anotherCountry).getName(); 
    int i = this.name.compareTo(anotherCountryName); 
    if(i < 0){ 
     return -1; 
    } else { 
     return 0; 
    } 
} 

錯誤:

@Override 
public int compareTo(Object anotherCountry) throws ClassCastException { 
    if (!(anotherCountry instanceof Country)) 
     throw new ClassCastException("A Country object expected."); 
    String anotherCountryName = ((Country) anotherCountry).getName(); 
    return this.name.compareTo(anotherCountryName); 

Description Resource Path Location Type 

名稱衝突:類型國家的方法的compareTo(對象)具有相同的擦除作爲的compareTo (T)類型Comparable但不覆蓋Country.java/Lab2_prob 4/src行17 Java問題

Description Resource Path Location Type 
The method compareTo(Object) of type Country must override or implement a supertype method Country.java /Lab2_prob 4/src line 17 Java Problem 

和類:

public class Country implements Comparable<Country>{ 
    private String name; 
    private String capital; 
    private int area; 

Description Resource Path Location Type 

類型國家必須實現繼承抽象方法Comparable.compareTo(國家或地區)Country.java/Lab2_prob 4/SRC 2行的Java問題

+2

您的'Country'類是否擴展了'Comparable '? –

+2

你真的得到了什麼問題或錯誤? – DNA

+0

抱歉只是添加了錯誤。 –

回答

16

Country類應該實現Comparable

public class Country implements Comparable<Country> 

然後你compareTo方法應該是這樣的:

@Override 
public int compareTo(Country anotherCountry) { 
    return anotherCountry.getName().compareTo(this.name); 
} 

compareTo簽名。參數可以(並且必須)是Country而不是Object。這是因爲Comparable上的泛型類型參數。好處是你不必再檢查類型。缺點是你只能比較Country與其他Country對象(或它的子類型),但在大多數情況下,這是你想要的東西。如果沒有,你必須改變類型參數。例如。如果您使用Comparable<Object>,則compareTo的簽名可以再次爲Object。如果您願意,可以閱讀泛型here

+1

只記得'Comparable'是一個界面。對不起,錯誤。 –

+0

您能否請您檢查我建議的修復後得到的錯誤?漂亮請 –

+0

編輯我的答案 –

4

一個Comparable應該返回:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

但是,您的代碼只返回-1或0,其中我不正確;這意味着this可以小於其他對象,或者相等,但不會更大!

沒有必要修改name.compareTo()返回的值 - 您可以直接返回它們。