我有一个时间范围,我想根据开始时间对时间进行排序 例如:
Range = {[3,5] , [1,10] ,[6,7] ,[4,10]}
After sorting
{ [1,10] , [3,5] , [4,10] , [6,10]}
如何使用 Collections.sort
或任何其他方法来完成。
我是否必须定义一个类来排序,即
class interval{
int start;
int end;
}
我有上面的结构,我想根据开始对它进行排序;
即 Collections.sort(interval)//相对于开始;
最佳答案
使用 Collections.sort
与自定义 Comparator<T>
:
Collections.sort(times, new Comparator<interval>() {
public int compare(interval a, interval b) {
int res = Integer.compare(a.start, b.start);
if (res != 0) return res;
return Integer.compare(a.end, b.end);
}
});
另一种编码方式是实现 Comparable<T>
interval
中的界面类。
关于java - 在java中对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25938973/