我有一个二维2D数组,我正在尝试根据第二列对数组进行排序。我正在尝试Costi Ciudatu here发布的答案,但我收到以下错误:
Arrays类型中的方法sort(T [],Comparator)不适用于参数(double [] [],ArrayComparator)
我该如何解决?
到目前为止我的代码是:
import java.util.Comparator;
class ArrayComparator implements Comparator<Comparable[]> {
private final int columnToSort;
private final boolean ascending;
public ArrayComparator(int columnToSort, boolean ascending) {
this.columnToSort = columnToSort;
this.ascending = ascending;
}
public int compare(Comparable[] c1, Comparable[] c2) {
int cmp = c1[columnToSort].compareTo(c2[columnToSort]);
return ascending ? cmp : -cmp;
}
}
和
import java.util.Arrays;
import java.util.Comparator;
public class Convex {
public static void mysort(double points[][], int n){
Arrays.sort(points, new ArrayComparator(1, true));
}
}
答案 0 :(得分:1)
原始double
不是Comparable
,因此您需要调整此比较器以比较double[]
:
class ArrayComparator implements Comparator<double[]> {
private final int columnToSort;
private final boolean ascending;
public ArrayComparator(int columnToSort, boolean ascending) {
this.columnToSort = columnToSort;
this.ascending = ascending;
}
public int compare(double[] c1, double[] c2) {
int cmp = Double.compare(c1[columnToSort], c2[columnToSort]);
return ascending ? cmp : -cmp;
}
}