简体   繁体   English

Java中double和string的ArrayList的ArrayList按double排序

[英]Sorting ArrayList of ArrayList of double and string by the double in Java

I have an arraylist of arraylist which contains a string and an integer.我有一个 arraylist 的 arraylist,它包含一个字符串和一个整数。 It looks like:看起来像:

ArrayList<ArrayList> l= {{1.02,"string1"},{0.33,"string2"},{1.15,"string3"},}; 

and I want to sort it by the order of the double number to look like this:我想按双数的顺序对其进行排序,如下所示:

ArrayList<ArrayList> l= {{0.33,"string2"},{1.02,"string1"},{1.15,"string3"},};

I wrote this code but it doesn't work for me and I don't know where is the problem:我写了这段代码,但它对我不起作用,我不知道问题出在哪里:

public void listSorting(ArrayList<ArrayList> l){
    int min=0;
    for(int i=0;i<l.size();i++){
        min=i;
        for(int j=i+1;j<l.size();j++){
            if((double)(l.get(i).get(0)) < (double)(l.get(min).get(0))){
                min=j;
            }
        }
        ArrayList temp=new ArrayList<>();
        temp.add(l.get(i));
        l.get(i).add(l.get(min));
        l.get(min).add(temp);
    }
}

You made three mistakes:你犯了三个错误:

  • Index of double in your list is zero, not one,列表中double索引为零,而不是一,
  • The inner loop needs to compare min item with item at index j , not i ,内循环需要将min项与索引j处的项进行比较,而不是i
  • When you swap two elements of type ArrayList , do not create a new array list.交换ArrayList类型的两个元素时,不要创建新的数组列表。

Here is how you can fix your code:以下是修复代码的方法:

for(int i=0;i<l.size();i++){
    min=i;
    for(int j=i+1;j<l.size();j++){
        if((double)(l.get(j).get(0)) < (double)(l.get(min).get(0))){
            min=j;
        }
    }
    ArrayList temp=l.get(i);
    l.set(i, l.get(min));
    l.set(min, temp);       
}

Demo.演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM