I have following class. In this, Iris is another class with some attributes.
public class Helper {
Iris iris;
double distance;
public Helper(Iris iris, double distance) {
this.iris = iris;
this.distance = distance;
}
}
I want to sort an array list of this (i.e List < Helper > helperList), descending based on distance parameter. I have written the following method but it is not working.
public void sort(){
for(int k=0; k < helperList.size(); k++)
{
double distance = helperList.get(k).distance;
for(int l=0; l < helperList.size(); l++)
{
Helper temp = helperList.get(l);
if( distance < temp.distance )
{
helperList.set(l, helperList.get(k));
helperList.set(k, temp);
}
}
}
}
Can anybody suggest a solution?
解决方案
Why don't you get your Helper class to implement Comparable interface and then use the in-built sort method offered by the Collections class.
Collections.sort(helperList)
I think that would solve the problem. Plus, this sort method is stable.
Implementing Comparable interface:
public class Helper implements Comparable{
Iris iris;
double distance;
public Helper(Iris iris, double distance) {
this.iris = iris;
this.distance = distance;
}
public int compareTo(Helper other) {
return new Double(this.distance).compareTo(new Double(other.distance));
}
}