2015-09-25 58 views
1
public class Human implements Comparable<Human> { 
    private int age; 
    private String name; 

    public Human(String givenName, int age) { 
     this.name = givenName; 
     this.age = age; 
    } 

    public String getName() { 
     return name; 
    } 

    public int getAge() { 
     return age; 
    } 

    public String introduce() { 
     return "Hey! I'm " + name + " and I'm " + age + " years old."; 
    } 

    public int CompareTo(Human h1, Human h2) { 
      int hum1 = h1.getAge(); 
      int hum2 = h2.getAge(); 
      System.out.println(hum1 - hum2); 
    } 
} 

該代碼使用年齡參數排序ArrayList和這個錯誤味精出現人類不是抽象的,不會重寫抽象方法compareTo(Human).solution?

./Human.java:6: error: Human is not abstract and does not override abstract method compareTo(Human) in Comparable public class Human implements Comparable

這裏有什麼錯?請幫助。

+0

您的CompareTo錯誤[link](http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-) –

回答

3

你想改變:

public int CompareTo(Human h1, Human h2) 

到:

public int compareTo(Human h_other) 

兩件事情:第一, 「C」 是小寫。其次,compareTo方法比較this另一個Human,所以它等同於(使用舊代碼):

public int compareTo(Human h_other) { 
    return CompareTo(this, other); 
} 
1

你已經得到了compareTo方法簽名是錯誤的。因此,編譯器告訴你,你還沒有按照指定實現接口Comparable。請參閱documentation以獲取正確的方法簽名。

它應該是這樣的:

public int compareTo(Human other) { 
    return Integer.compare(this.getAge(), other.getAge()); 
} 
1

在這裏,要實現Comparable接口,

public int CompareTo(Human h1); 

可比接口上面的方法只能有一個參數。你正在用兩個參數來實現它。那就是問題所在。

相關問題