按对象属性排序对象数组

时间:2013-05-27 01:30:52

标签: java arrays sorting object properties

我知道有很多这样的问题,而且我一直在阅读很多,但我真的无法理解。我有一个用户定义的对象Team,它具有属性团队名称(String),batAvg(Double)和slugAvg(Double)。我想安排,按照下降batAvg的顺序打印队伍,然后按照下降slugAvg的顺序。我有一个所有团队的阵列,teamArray(Team [])。团队击球和击球平均值对阵列进行排序的最佳方法是什么?我尝试了很多东西,但似乎都没有。

1 个答案:

答案 0 :(得分: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;
    }

}