我有一个比较器,在给定列反转后对数组进行排序.我希望,这个比较器不仅适用于int [],它也适用于其他数字类型.我该怎么做?
比较器的代码在这里:
public class ReverseComparator implements Comparator<int[]> {
int col;
public ReverseComparator(int col) {
this.col = col;
}
@Override
public int compare(int[] a, int[] b) {
if (a[col - 1] > b[col - 1]) {
return -1;
} else if (a[col - 1] < b[col - 1]) {
return 1;
} else {
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我改变了,但总是错的,我不知道......
public class ReverseComparator implements Comparator<T extends Number[]> {
int col;
public ReverseComparator(int col) {
this.col = col;
}
@Override
public int compare(T[] a, T[] b) {
if (a[col - 1] > b[col - 1]) {
return -1;
} else if (a[col - 1] < b[col - 1]) {
return 1;
} else {
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你必须制作ReverseComparator泛型,那么你要用它声明type参数.并给它一定的界限:
public class ReverseComparator<T extends Number & Comparable<T>> implements Comparator<T[]> {
@Override
public int compare(T[] a, T[] b) {
// Write your comparison logic here
// Note that just normal arithmetic operators won't work here.
}
}
Run Code Online (Sandbox Code Playgroud)
我给了type参数两个边界,因为我们只想比较可比较的数字.给予Comparable<T>作为第二势必让你使用compareTo()的方法进行比较.
另请注意,例如,这对基本类型数组不起作用int[][].你必须有Integer[][],或Float[][]等
| 归档时间: |
|
| 查看次数: |
391 次 |
| 最近记录: |