2015-04-03 31 views
0

在ArrayList中,我有三个我希望在第三个数组上排序的double []数组。第三个数组也是未排序的。在单个阵列上按ArrayList索引(行)对三个阵列排序

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

+0

什么是期望的输出? – Eran 2015-04-03 09:59:22

+0

我已经在上面的“变成:”下展示了它。每个数组应该显示在一列中,按第三列排序。 – noumenal 2015-04-03 10:06:11

+0

我以为那是你已经得到的输出。 – Eran 2015-04-03 10:07:13

回答

1

我得到了d希望的输出。我测试了下面的代码。不明白为什么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]); 
    } 
}; 
} 
+0

这适用于该示例。但是,实际的阵列比示例中的要长得多。当插入实际的数组时,输出看起来是颠倒的。我不知道为什么。有没有办法只返回一个循环的头部(即前5行)? – noumenal 2015-04-03 11:22:09

+0

糟糕。我错误地初始化了尺寸。并从那里它只是: 的for(int i = 0; I <5;我++){ \t \t \t对(INT O = 0;○<3;○++){ \t \t \t System.out的。 print(levelList.get(o)[i] +“,”); \t \t} \t \t \t System.out.println(); \t} – noumenal 2015-04-03 12:14:35