2013-05-27 132 views
0

我知道有很多這樣的問題,我一直在閱讀很多,但我真的無法弄清楚。我有一個用戶定義的對象Team,它具有屬性組名(String),batAvg(Double)和slugAvg(Double)。我想安排,並按照降序batAvg的順序打印隊伍,然後按降序slugAvg排列。我有一組所有的球隊,teamArray(Team [])。團隊擊球和平均擊球的最佳方式是什麼?我嘗試了一堆東西,但似乎沒有任何工作。按對象的屬性排序對象的數組

+1

*「我已經讀了很多,但我真的無法弄清楚。」 *是什麼讓你覺得什麼我們寫會突然幫你圖出來? –

回答

0

請檢查下面的代碼,

import java.util.Arrays; 
import java.util.Comparator; 


public class Team { 
    private String name; 
    private double batAvg; 
    private double slugAvg; 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public double getBatAvg() { 
     return batAvg; 
    } 
    public void setBatAvg(double batAvg) { 
     this.batAvg = batAvg; 
    } 
    public double getSlugAvg() { 
     return slugAvg; 
    } 
    public void setSlugAvg(double slugAvg) { 
     this.slugAvg = slugAvg; 
    } 


    public static void main(String[] argv){ 
     Team[] teams = new Team[2]; //TODO, for testing.. 
     Arrays.sort(teams, new TeamComparator()); //This line will sort the array teams 
    } 
} 

class TeamComparator implements Comparator<Team>{ 

    @Override 
    public int compare(Team o1, Team o2) { 
     if (o1.getSlugAvg()==o2.getSlugAvg()){ 
      return 0; 
     } 
     return o1.getSlugAvg()>o2.getSlugAvg()?-1:1; 
    } 

}