int compare(T o1, T o2);
接口源码描述:
Compares its two arguments for order. Returns a negative integer,
zero, or a positive integer as the first argument is less than, equal
to, or greater than the second.
翻译:有序比较它的两个参数,返回一个正数,零或者负数;当第一个参数小于,等于或大于第二个参数。
@throws NullPointerException if an argument is null and this
comparator does not permit null arguments
@throws ClassCastException if the arguments’ types prevent them from
being compared by this comparator.
翻译:此函数不允许空参数,会抛出 NullPointerException
如果参数的类型组织它们被比较器比较,会抛出 ClassCastException
2020/01/02 跟新
现在的我当然不会写这么不优雅的代码啦,附上优美的代码:
public void test() {
int[][] intervals = new int[][]{{1, 3}, {2, 3}, {0, 1}, {1, 2}};
Collections.sort(Arrays.asList(intervals), (a, b) -> a[0] < b[0] ? -1 : a[0] == b[0] ? a[1] - b[1] : 1);
for (int[] in : intervals)
System.out.println(in[0] + " " + in[1]);
}
例子
写一个 int[] 类型的比较器
private class IntervalComparator implements Comparator<int[]> {
@Override
public int compare(int[] a, int[] b) {
return a[0] < b[0] ? -1 : a[0] == b[0] ? 0 : 1;
}
}
调用:
int[][] intervals = new int[][]{{1, 3}, {2, 3}, {0, 1}};
Collections.sort(Arrays.asList(intervals), new IntervalComparator());
for (int[] in : intervals)
System.out.println(in[0] + " " + in[1]);
结果如下:
0 1
1 3
2 3