比较者没有用日期对我的班级进行排序

时间:2014-09-10 20:43:14

标签: java android sorting

我有一个日,月的班级。我插入随机日期,我排序后看起来像那样?为什么呢?

  • 1/9
  • 2/9
  • 3/9
  • 7/9
  • 9/9
  • 10/9
  • 5/9
  • 11/9

我得到了"时间"通过从数据库获取它,我将数据作为ArrayList返回 代码:

public ArrayList<ClockModel> getDay(String workName){
        try {
            open();
            ArrayList<ClockModel> list = new ArrayList<ClockModel>();
            Cursor c = null;
            c = myDb.query(TABLE_DAY, null,"workName = ?", new String[] {workName}, null, null, null);
            while (c.moveToNext()) {
                Clock clock = new Clock(
                        c.getInt(0), //id
                        c.getString(1),//workName
                        c.getInt(2), //dateDay
                        c.getInt(3),//dateMouth
                        c.getInt(4),//dateYear
                );


                Collections.sort(list,dateCompare); 



                list.add(clock);        
            }       
            return list;
        } catch (Exception e) {
            return null;
        }finally{
            close();
        }
    }





    Comparator<ClockModel> dateCompare = new Comparator<ClockModel>() {

        @Override
        public int compare(ClockModel o1, ClockModel o2) {

            int dd1 = o1.getDateDay();
            int mm1 = o1.getDateMonth();

            int dd2 = o2.getDateDay();
            int mm2 = o2.getDateMonth();

            if (mm1 > mm2) {
                return 1;
            } else if (mm1 < mm2) {
                return -1;
            } else { // ==

                if (dd1 > dd2) {
                    return 1;
                } else if (dd1 < dd2) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    }; 

1 个答案:

答案 0 :(得分:2)

比较方法看起来很好。你确定这个错误正好在这里吗?如果是你的类ClockModel,那么我建议你仔细检查它=)

顺便说一下,你可以像这样使用Integer.compare(int,int)来简化代码:

Comparator<ClockModel> dateCompare = new Comparator<ClockModel>() {

    @Override
    public int compare(ClockModel o1, ClockModel o2) {

        int monthCompare = Integer.compare(o1.getDateMonth(), o2.getDateMonth());
        int dayCompare = Integer.compare(o1.getDateDay(), o2.getDateDay());

        return (monthCompare != 0) ? monthCompare : dayCompare;

    }
}