I have an arraylist of arraylist which contains a string and an integer. 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:
double
in your list is zero, not one,min
item with item at index j
, not i
,ArrayList
, do not create a new array list.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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.