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
Helperclass to implementComparableinterface and then use the in-built sort method offered by the Collections class.I think that would solve the problem. Plus, this
sortmethod is stable.http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
Implementing Comparable interface: