Sorting array lists in Java
•
Java
I have finished class Here, iris is another class with certain properties
public class Helper { Iris iris; double distance; public Helper(Iris iris,double distance) { this.iris = iris; this.distance = distance; } }
I want to sort the array list (i.e. list < helper > helperlist) in descending order according to the distance parameter I wrote the following method, but it didn't work
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 anyone propose a solution?
Solution
Why not let the helper class implement the comparable interface and then use the built-in sorting method provided by the collections class
Collections.sort(helperList)
I think this will solve the problem In addition, this sort method is very 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
Implement the 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)); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码