Question

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]);
}
Was it helpful?

Solution

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]));
    }    
}

OTHER TIPS

I suppose you forgot, in the code you wrote, to switch back to double in your comparator... (I mean, as you said you tried with String and it worked, I suppose that is why there remains some strange String[] that clearly should not be there)

If I assume I should read double[] row1 = (double[])o1, then the problem is that you can't call .compareTo on a double. You should just substract the values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top