0

I have a 2-dimensional double array and I want to sort it based on the second column. I wrote this code, but I got this error in the last line "double can not be dereferenced". It seems it works with string but not for array. any help appreciated.

import java.util.Arrays;
import java.util.Comparator;

public class Sort { 
    public static void main(String args[]){
        //Array to sort
        double[][] X = new double[][]{
                {1.2,2,1,3.1},
                {1,2.7,3.3},
                {1,2.3,3.1},
                {1.5,3.2,2.4};

        //Sort the array by column 2
        Arrays.sort(X, new ColumnComparator(2));
    }
}


//Class that extends Comparator
class ColumnComparator implements Comparator {
    int columnToSort;
    ColumnComparator(int columnToSort) {
        this.columnToSort = columnToSort;
    }
//overriding compare method
    public int compare(Object o1, Object o2) {
        double[] row1 = (double[]) o1;
    double[] row2 = (double[]) o2;
    //compare the columns to sort
    return row1[columnToSort].compareTo(row2[columnToSort]);
}
4

2 回答 2

1

我想你忘记了,在你写的代码中,在你的比较器中切换回 double ......(我的意思是,正如你所说,你尝试使用 String 并且它有效,我想这就是为什么仍然有一些奇怪的 String[]显然不应该在那里)

如果我假设我应该阅读 double[] row1 = (double[])o1,那么问题是您不能在 double 上调用 .compareTo。您应该只减去这些值。

于 2013-03-14T23:36:56.090 回答
1
public class SecondColumnComparator implements Comparator<double[]> {
    @Override
    public int compare(double[] row1, double[] row2) {
        return Double.compare(row1[1], row2[1]);
        // or, before Java 7:
        // return Double.valueOf(row1[1]).compareTo(Double.valueOf(row2[1]));
    }    
}
于 2013-03-14T23:40:14.963 回答