How to use Comparator in Java to sort

后端 未结 14 2065
时光取名叫无心
时光取名叫无心 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 03:04

    Two corrections:

    1. You have to make an ArrayList of People objects:

      ArrayList preps = new ArrayList(); 
      
    2. After adding the objects to the preps, use:

      Collections.sort(preps, new CompareId());
      

    Also, add a CompareId class as:

    class CompareId implements Comparator {  
        public int compare(Object obj1, Object obj2) {  
            People t1 = (People)obj1;  
            People t2 = (People)obj2;  
    
            if (t1.marks > t2.marks)  
                return 1;   
            else  
                return -1;
        }  
    }
    

提交回复
热议问题