javasortingtype-2-dimension

Sort a 2-dimensional array


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

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