Sorting a double value of an object within an arrayList

后端 未结 5 964
佛祖请我去吃肉
佛祖请我去吃肉 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:46

    To use a Comparator:

    Collections.sort(myList, new Comparator() {
        @Override
        public int compare(Chromosome c1, Chromosome c2) {
            return Double.compare(c1.getScore(), c2.getScore());
        }
    });
    

    If you plan on sorting numerous Lists in this way I would suggest having Chromosome implement the Comparable interface (in which case you could simply call Collections.sort(myList), without the need of specifying an explicit Comparator).

提交回复
热议问题