Sorting array list in Java

后端 未结 4 1007
悲哀的现实
悲哀的现实 2021-01-14 06:22

I have following class. In this, Iris is another class with some attributes.

public class Helper {

    Iris iris;
    double distance;

    public Helper(Ir         


        
4条回答
  •  梦谈多话
    2021-01-14 06:57

    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.

    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:

    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));
    
        }
    }
    

提交回复
热议问题