How to use Comparator in Java to sort

后端 未结 14 1803
时光取名叫无心
时光取名叫无心 2020-11-22 02:19

I learned how to use the comparable but I\'m having difficulty with the Comparator. I am having a error in my code:

Exception in thread \"main\" java.lang.C         


        
14条回答
  •  不思量自难忘°
    2020-11-22 02:59

    Here's a super short template to do the sorting right away :

    Collections.sort(people,new Comparator(){
       @Override
       public int compare(final Person lhs,Person rhs) {
         //TODO return 1 if rhs should be before lhs 
         //     return -1 if lhs should be before rhs
         //     return 0 otherwise (meaning the order stays the same)
         }
     });
    

    if it's hard to remember, try to just remember that it's similar (in terms of the sign of the number) to:

     lhs-rhs 
    

    That's in case you want to sort in ascending order : from smallest number to largest number.

提交回复
热议问题