0

我知道有很多这样的问题,我已经阅读了很多,但我真的无法弄清楚。我有一个用户定义的对象 Team,它具有团队名称 (String)、batAvg (Double) 和 slugAvg (Double) 属性。我想按 batAvg 降序排列和打印团队,然后按 slugAvg 降序排列。我有一个包含所有团队的数组,teamArray (Team[])。按球队的击球率和打击率对这个数组进行排序的最佳方法是什么。我已经尝试了很多东西,但似乎都不起作用。

4

1 回答 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;
    }

}
于 2013-05-27T01:47:21.113 回答