how to sort an ArrayList in ascending order using Collections and Comparator

后端 未结 6 797
轮回少年
轮回少年 2020-12-06 07:36

How to sort an ArrayList in ascending order using Comparator? I know how to sort it in descending order using:

Comparator mycompar         


        
6条回答
  •  时光说笑
    2020-12-06 08:15

    Use the default version:

    Collections.sort(myarrayList);
    

    Of course this requires that your Elements implement Comparable, but the same holds true for the version you mentioned.

    BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.

    List list = new ArrayList();
    // now fill up the list
    
    // compile error here unless MyClass implements Comparable
    Collections.sort(list); 
    

提交回复
热议问题