如何连续两次使用比较器?

时间:2015-04-09 14:07:13

标签: java android

我正在尝试使用比较器按时间和点对列表进行排序,时间更重要,如果对象具有相同的时间,则比较点。

这是我尝试过的,但它并没有完全符合我的想法。

我是否错误地比较了它?

Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
            public int compare(DatabaseGuard p1, DatabaseGuard p2) {
                int endShiftInt = (int) p1.getEndShift()/1000;
                int endShiftInt2 = (int) p2.getEndShift()/1000;

                if(endShiftInt == endShiftInt2) {
                    Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
                        public int compare(DatabaseGuard p1, DatabaseGuard p2) {
                            return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
                        }
                    });
                }
                return Integer.valueOf(endShiftInt).compareTo(endShiftInt2);
            }
        });

我也试过这个:

Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
            public int compare(DatabaseGuard p1, DatabaseGuard p2) {
                return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
            }
        });

        //sortUsers in order of last Time They Guarded, those with a higher number is more recent, then lower numbers first
        Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
            public int compare(DatabaseGuard p1, DatabaseGuard p2) {
                int endShiftInt = (int) p1.getEndShift()/1000;
                int endShiftInt2 = (int) p2.getEndShift()/1000;

                return Integer.valueOf(endShiftInt).compareTo(endShiftInt2);
            }
        });

2 个答案:

答案 0 :(得分:4)

这比那简单得多。使用类似的东西:

    Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {

        public int compare(DatabaseGuard p1, DatabaseGuard p2) {
            int endShiftInt = (int) p1.getEndShift() / 1000;
            int endShiftInt2 = (int) p2.getEndShift() / 1000;

            if (endShiftInt == endShiftInt2) {
                return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
            }
            return Integer.valueOf(endShiftInt).compareTo(endShiftInt2);
        }
    }
    );

基本上 - 如果第一个属性相同则应该返回第二个属性之间的差异。

答案 1 :(得分:0)

没有必要使用两个不同的比较器调用两次。用以下代码替换您的代码。

Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
    public int compare(DatabaseGuard p1, DatabaseGuard p2) {
       int endShiftInt = (int) p1.getEndShift()/1000;
       int endShiftInt2 = (int) p2.getEndShift()/1000;

       if (endShiftInt == endShiftInt2) {
           return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
       }
       return endShiftInt - endShiftInt2;  // I make a little Optimization here
   }
});