public class ActiveAlarm { public long timeStarted; public long timeEnded; private String name = ""; private String description = ""; private String event; private boolean live = false; }
和List<ActiveAlarm>骗局。如何按升序排序timeStarted,然后按timeEnded?有人可以帮忙吗?我知道在C ++中具有通用算法和重载运算符<,但是我是Java新手。
List<ActiveAlarm>
timeStarted
timeEnded
C ++
<
使ActiveAlarm实现Comparable<ActiveAlarm>或Comparator<ActiveAlarm>在单独的类中实现。然后致电:
ActiveAlarm
Comparable<ActiveAlarm>
Comparator<ActiveAlarm>
Collections.sort(list);
要么
Collections.sort(list, comparator);
通常,Comparable<T>如果有一个单一的“自然”排序顺序,则实施是个好主意…否则(如果你碰巧想要按特定顺序进行排序,但可能同样容易地希望使用另一个顺序),则最好实现Comparator<T>。老实说,这种特殊情况可能会发生任何一种……但是我可能会坚持使用更灵活的Comparator<T>选择。
Comparable<T>
Comparator<T>
编辑:示例实现:
public class AlarmByTimesComparer implements Comparator<ActiveAlarm> { @Override public int compare(ActiveAlarm x, ActiveAlarm y) { // TODO: Handle null x or y values int startComparison = compare(x.timeStarted, y.timeStarted); return startComparison != 0 ? startComparison : compare(x.timeEnded, y.timeEnded); } // I don't know why this isn't in Long... private static int compare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } }