2

I try to sort a 2D double array (double[][]) on the first value. example: {1.0226342823592962,0.0}, {1.0395582845873155,1.0} starting with the biggest value. This is the code I use (java generated half of it)

java.util.Arrays.sort(indexMatrix, new java.util.Comparator<double[]>() {

        @Override
        public int compare(double[] o1, double[] o2) {
            // TODO Auto-generated method stub
            return 0;
        }


    });

However my 'indexMatrix' is not changed after. I think it has something to do with public int compare, because the values are so close to each other, if you cast them to int they will all be 1 and cannot be sorted. Or is it something else?

4

4 回答 4

1

为什么将它们转换为整数?只需Double.compareTo(Double)在您的排序方法中使用方法:

public static void main(String[] args) {

    double[][] indexMatrix = new double[][] {
                  new double[] { 1.02, 100 }, 
                  new double[] { 1.03, 123 },
                  new double[] { 1.01, 321 } };

    Arrays.sort(indexMatrix, new Comparator<double[]>() {
        @Override
        public int compare(double[] o1, double[] o2) {
            return Double.compare(o2[0], o1[0]);
        }
    });

    for (double[] d : indexMatrix)
        System.out.println(Arrays.toString(d));
}

输出:

[1.03, 123.0]
[1.02, 100.0]
[1.01, 321.0]
于 2013-06-07T08:22:06.833 回答
1

不,您不会将双打转换为整数。Anint正是compare()预期的返回参数。它应该返回 0 如果o1o2相等,一个值小于 0 ifo1 < o2和一个值大于 0 if o1 > o2。您可以Double.compare()为此使用:

java.util.Arrays.sort(indexMatrix, new java.util.Comparator<double[]>() {
    @Override
    public int compare(double[] o1, double[] o2) {
        // note that o2 comes first here to sort in descending order
        return Double.compare(o2[0], o1[0]);
    }
});
于 2013-06-07T08:27:55.600 回答
1

你必须实现 compare 方法,你所拥有的只是一个模板。它没有改变,因为默认返回 0 意味着比较的值相等。其他返回值为-1和+1,根据实际情况而定。

于 2013-06-07T08:20:33.577 回答
0

使用 Java8+

Arrays.sort(indexMatrix, (Double[] o1, Double[] o2) -> Double.compare(o1[0], o2[0]));
于 2019-08-06T22:20:36.087 回答