按单个数组上的ArrayList索引(行)对三个数组进行排序



在ArrayList中,我有三个双[]数组,希望在第三个数组上进行排序。第三个数组也是未排序的。

public class LevelList extends ArrayList<double[]> {

我的比较器比较替身:

import java.util.Comparator;
public class Linearize {
     static final Comparator<double[]> RATIO_ORDER = 
             new Comparator<double[]>() {
                 @Override
                 public int compare(double[] d1, double[] d2) {
                     //Sort the ratios based on the fraction column 2
                     return Double.compare(d1[2], d2[2]);
                 }
         };
}

然后我打电话给:

Collections.sort(levelList, Linearize.RATIO_ORDER);
levelList.println();

然而,这只会导致对ArrayList中数组的顺序进行排序。

在伪代码中,我希望实现的是:

For Each Row of ArrayList at Index i
Sort on Array 3

这样这个输入:

[1.0][2.0][2.1]
[2.0][5.0][2.2]
[1.0][5.0][1.0]

变为:

[1.0][5.0][1.0]
[1.0][2.0][2.1]
[2.0][5.0][2.2]

因为:2.2>2.1>1.0

我得到了所需的输出。我测试了以下代码。不明白为什么级别列表必须扩展arraylist,因此删除了它。

public class TestLevelSorting {
public static void main(String[] args) {
    List<double[]> levelList = new ArrayList<double[]>();
    double[] items1 = {1.0, 2.01, 2.1};
    double[] items2 = {2.0, 5.0, 2.2};
    double[] items3 = {1.0, 5.0, 1.0};
    levelList.add(items1);
    levelList.add(items2);
    levelList.add(items3);
    Collections.sort(levelList, Linearize.RATIO_ORDER);
    for(double[] item : levelList){
        System.out.println(Arrays.toString(item));
    }
}
}
class Linearize {
static final Comparator<double[]> RATIO_ORDER = new Comparator<double[]>() {
    @Override
    public int compare(double[] d1, double[] d2) {
        // Sort the ratios based on the fraction column 2
        return Double.compare(d1[2], d2[2]);
    }
};
}

最新更新