2016-02-29 73 views
0

我需要排序包含我創建的兩種不同類的數組的排序方面的幫助。我的兩個班都是具有姓名和年齡的「人」,然後我有一個從人類繼承而來的班級「物理學家」,但他們開始學習時也有一個「開始年」的領域。事情是這樣的:用兩個不同的對象對數組排序

public class Human implements Comparable<Human> { 

    private int age; 
    private String name; 

    public Human(int agein, String namein) { 
     age = agein; 
     name = namein; 
    } 
    public int compareTo(Human other) { 

     return Integer.compare(this.age, other.age);  
    } 
} 

public class Fysiker extends Human { 

    private int year; 

    public Fysiker(int startYear, int ageIn, String nameIn){ 

     super(ageIn, nameIn); 
     } 

    public int compareTo(Fysiker other) { 

     if(other instanceof Fysiker && this.getAge() == other.getAge()) { 
      return Integer.compare(this.year, other.year); 
     } 
     else { 
      return Integer.compare(this.getAge(), other.getAge()); 
     } 

    } 
} 

我要的是,當我創建人類和物理學家混合陣列和排序的話,我希望它按年齡排序,如果兩個物理學家是同齡人,那麼他們應該按照他們的年份排序。例如像這樣:

輸入:

名:Alex,年齡:32,時間:2007年

名:尼爾斯,年齡:30,年:2008

名:安德斯,年齡:32年:2003

名:埃裏克年齡:18

名:奧洛夫,年齡:31

有序數組:

名:埃裏克年齡:18

名:尼爾斯,年齡:30,年:2008

名:奧洛夫,年齡:31

名:安德斯年齡:32年:2003

名:Alex,年齡:32,時間:2007年

都是我的compareTo方法錯了嗎?或者爲什麼它不工作? 我沒有得到任何錯誤,數組只是按年齡排序,然後沒有更多的發生。

我很感謝您的幫助!

public int compareTo(Fysiker other) { 

    if(other instanceof Fysiker && this.getAge() == other.getAge()) { 
     return Integer.compare(this.year, other.year); 
    } 
    else { 
     return Integer.compare(this.getAge(), other.getAge()); 
    } 

} 

將永遠不會被調用,因爲你人這麼簽名不匹配(如通過阿爾森在評論中提到)的數組:

+3

添加的語言關鍵字,請,使得它更容易。 Java的? – Roger

+0

它是* Java *嗎?如果是,請添加相應的標籤,請 –

+0

是的,它是Java。對不起,我忘了這件事。 –

回答

1

這種方法。

這應該工作:

public int compareTo(Human other) { 

    if(other instanceof Fysiker && this.getAge() == other.getAge()) { 
     return Integer.compare(this.year, ((Fysiker) other).year); 
    } 
    else { 
     return Integer.compare(this.getAge(), other.getAge()); 
    } 

} 
0

或者對執行Comparable,你也可以在排序時使用自定義Comparator。特別是對於Java 8,通過將Comparator.comparingComparator.thenComparing與自定義lambda函數進行鏈接,這對於比較多個字段來說也更加簡單。

在任何方式,Comparator(或Comparable)必須接受任何形式的Human並檢查它是否是一個Fysiker與否。

List<Human> humans = Arrays.asList(
     new Fysiker(2007, 32, "Alex"), 
     new Fysiker(2008, 30, "Nils"), 
     new Fysiker(2003, 32, "Anders"), 
     new Human(18, "Erik"), 
     new Human(31, "Olof") 
); 
Collections.sort(humans, Comparator 
     .comparing((Human h) -> h.age) 
     .thenComparing((Human h) -> h instanceof Fysiker ? ((Fysiker) h).year : 0)); 
humans.forEach(System.out::println); 

輸出:

Human Erik 18 
Fysiker Nils 30 2008 
Human Olof 31 
Fysiker Anders 32 2003 
Fysiker Alex 32 2007