android,比较器排序错误

时间:2014-09-26 18:44:58

标签: android sorting comparator

我有一个比较器按3个值排序:

  1. ORDER_BY_Points
  2. ORDER_BY_Gdif //目标差异
  3. ORDER_BY_Goals
  4. 首先,我从json字符串中获取一个数组。我将数组发送到StandingsSort.ORDER_BY_RULES

    Arrays.sort(addressArray, StandingsSort.ORDER_BY_RULES);
    

    这是我的代码:

    static final Comparator<Standings> ORDER_BY_Points = new Comparator<Standings>() {
        public int compare(Standings a1, Standings a2) {
            return a1.points.compareTo(a2.points);
        }
    };
    static final Comparator<Standings> ORDER_BY_Gdif = new Comparator<Standings>() {
        public int compare(Standings a1, Standings a2) {
            return a1.Gdif.compareTo(a2.Gdif);
        }
    };
    static final Comparator<Standings> ORDER_BY_Goals = new Comparator<Standings>() {
        public int compare(Standings a1, Standings a2) {
            return a1.goalsP.compareTo(a2.goalsP);
        }
    };
    
    static final Comparator<Standings> ORDER_BY_RULES = new Comparator<Standings>() {
        public int compare(Standings a1, Standings a2) {
            int i = ORDER_BY_Points.compare(a1,a2);
            if(i == 0){
                i = ORDER_BY_Gdif.compare(a1,a2);
                if(i == 0){
                    i = ORDER_BY_Goals.compare(a1,a2);
                }
            }
            return i;
        }
    };
    
    class Standings {
    
        String teamName;
        String goalsP;
        String goalsM;
        String Gdif;
        String points;
        @Override
        public String toString() {
            return "" + teamName + ","  + goalsP + ":" + goalsM + "," + Gdif + "," + points + "";
        }
        public Standings(String teamName, String goalsP,
                    String goalsM, String Gdif, String points) {
            super();
            this.teamName = teamName;
            this.goalsP = goalsP;
            this.goalsM = goalsM;
            this.Gdif = Gdif;
            this.points = points;
        }
    }
    

    但结果不行!结果如下

    Name, Goals, GDif, Points
    Team,11:9,2,10
    Team,5:3,2,10
    Team,9:2,7,11
    Team,0:6,-6,2
    Team,3:9,-6,2
    Team,6:9,-3,3
    Team,8:13,-5,3
    Team,8:9,-1,5
    Team,8:11,-3,5
    Team,8:7,1,5
    

    为什么比较器排序错误?

1 个答案:

答案 0 :(得分:2)

由于您将点存储为String s,&#34; 10&#34;来自&#34; 2&#34;,&#34; 3&#34;和&#34; 5&#34;。如果您想按数值顺序比较它们,则需要先将它们转换为int

同样,Gdif和Goals被比作String s,这可能不是你想要的。