java - Comparator not sorted my class with dates -
i have class day,month. insert random dates , after sorted looks that? why?
- 1/9
- 2/9
- 3/9
- 7/9
- 9/9
- 10/9
- 5/9
- 11/9
i getting "time" getting database , return data arraylist code:
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; } } } };
the compare method looks fine. sure bug here? if yours class clockmodel, suggest double check it=)
and btw, can simplify code using integer.compare(int, int) this:
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; } }
Comments
Post a Comment