【问题标题】:Sorting a ArrayList<float[]> on two attributes within the float array对浮点数组中的两个属性对 ArrayList<float[]> 进行排序
【发布时间】:2015-04-07 23:41:05
【问题描述】:

我正在使用以下 ArrayList:ArrayList&lt;float[]&gt; notes = new ArrayList&lt;float[]&gt;();

我成功地对 float[] 数组的第一个元素进行了排序,没有任何问题。现在我也在尝试使用第二个属性对 ArrayList 进行排序。但是我无法设法在浮点数组的第二个元素上再次对列表进行排序,即。 float[1].

有什么提示吗?

【问题讨论】:

  • Arrays.sort 应该可以工作......
  • 什么意思? float[] 是一个原始数组 floats(不是对象)
  • @ryekayo 他正在尝试对包含数组的 List 进行排序,而不是每个列表中的数组,因此您需要使用 Collections.sort 而不是 Arrays.sort

标签: java arrays sorting arraylist


【解决方案1】:

您可以使用Collections.sort 对数组进行排序,然后使用您自己的Comparator 指定您希望如何对值进行排序。

ArrayList<float[]> notes = new ArrayList<float[]>();
//adding some dummy data to the list
notes.add(new float[]{5f,6f,1f});
notes.add(new float[]{5f,2f,1f});
notes.add(new float[]{5f,1f,1f});

//Use Collections.sort to sort Ascending values on the second value in the float arrays
Collections.sort(notes, new Comparator<float[]>() {
    @Override
    public int compare(float[] o1, float[] o2) {
        if (o1[1] > o2[1]){
            return 1;
        }else if(o1[1] < o2[1]){
            return -1;
        }
        return 0;
    }
});

//Output the values
for (float[] f : notes){
    System.out.println(Arrays.toString(f));
}

输出:

[5.0, 1.0, 1.0]
[5.0, 2.0, 1.0]
[5.0, 6.0, 1.0]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
相关资源
最近更新 更多