Sorting a double value of an object within an arrayList

后端 未结 5 963
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 15:07

I\'m trying to sort my custom class chromosome by the value of their score attribute which is a double. These chromosomes are stored within an ArrayList. I know I have to us

5条回答
  •  醉酒成梦
    2020-12-28 15:41

    I would implement the interface Comparable:

    public class Chromosome implements Comparable{
    
        private double score;
    
        public Chromosome(double score){
            this.score = score;
        }
        @Override
        public int compareTo(Chromosome o) {
            return new Double(score).compareTo( o.score);
        }
        @Override
        public String toString() {
            return String.valueOf(score);
        }
    }
    

    Note that i moved score inside the Class..

    Now you can use any Collection that is Sorted (like a TreeSet)

    If you insist on using the Arraylist you can use:

    ArrayList out = new ArrayList();
    out.add(new Chromosome(20));
    out.add(new Chromosome(15));
    System.out.println(out);
    Collections.sort(out);
    System.out.println(out);
    

    Result:

    [0.2, 0.15]
    [0.15, 0.2]
    

提交回复
热议问题