基于第二列在Java中对二维数组进行排序

时间:2016-01-23 17:46:45

标签: java arrays sorting comparator

我有一个二维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));               
    }
}

1 个答案:

答案 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;
    }
}