How to sort an ArrayList?

后端 未结 20 2523
有刺的猬
有刺的猬 2020-11-22 06:19

I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

List testList = new Arr         


        
20条回答
  •  再見小時候
    2020-11-22 07:01

    You can use Collections.sort(list) to sort list if your list contains Comparable elements. Otherwise I would recommend you to implement that interface like here:

    public class Circle implements Comparable {}
    

    and of course provide your own realization of compareTo method like here:

    @Override
        public int compareTo(Circle another) {
            if (this.getD()

    And then you can again use Colection.sort(list) as now list contains objects of Comparable type and can be sorted. Order depends on compareTo method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.

提交回复
热议问题