【问题标题】:Sort Three Arrays by ArrayList Index (Row) on a Single Array按单个数组上的 ArrayList 索引(行)对三个数组进行排序
【发布时间】:2015-04-03 09:56:13
【问题描述】:

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

public class LevelList extends ArrayList<double[]> {

我的比较器compares doubles

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

【问题讨论】:

  • 想要的输出是什么?
  • 我已经在上面的“变成:”下演示了这一点。每个数组都应显示在一列中,按第三列排序。
  • 我以为你已经得到了输出。
  • 我得到的实际上是 Col1 Col2 Col3 排序为 Col2 Col3 Col1,我猜这取决于每一列的值。
  • 为什么是extends ArrayList?避免从集合框架扩展类。

标签: java arrays sorting arraylist collections


【解决方案1】:

我得到了想要的输出。我测试了以下代码。不明白为什么 levellist 必须扩展 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]);
    }
};
}

【讨论】:

  • 这适用于示例。但是,实际的数组比示例中的要长得多。插入实际数组时,输出看起来是转置的。我不确定为什么。有没有办法通过循环只返回头部(即前 5 行)?
  • 糟糕。我错误地初始化了大小。从那里开始很简单: for(int i = 0; i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 2022-10-14
  • 2011-12-17
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 2022-01-28
相关资源
最近更新 更多