How to use Comparator in Java to sort

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

    You should use the overloaded sort(peps, new People()) method

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class Test 
    {
        public static void main(String[] args) 
        {
            List peps = new ArrayList<>();
    
            peps.add(new People(123, "M", 14.25));
            peps.add(new People(234, "M", 6.21));
            peps.add(new People(362, "F", 9.23));
            peps.add(new People(111, "M", 65.99));
            peps.add(new People(535, "F", 9.23));
    
            Collections.sort(peps, new People().new ComparatorId());
    
            for (int i = 0; i < peps.size(); i++)
            {
                System.out.println(peps.get(i));
            }
        }
    }
    
    class People
    {
           private int id;
           private String info;
           private double price;
    
           public People()
           {
    
           }
    
           public People(int newid, String newinfo, double newprice) {
               setid(newid);
               setinfo(newinfo);
               setprice(newprice);
           }
    
           public int getid() {
               return id;
           }
    
           public void setid(int id) {
               this.id = id;
           }
    
           public String getinfo() {
               return info;
           }
    
           public void setinfo(String info) {
               this.info = info;
           }
    
           public double getprice() {
               return price;
           }
    
           public void setprice(double price) {
               this.price = price;
           }
    
           class ComparatorId implements Comparator
           {
    
            @Override
            public int compare(People obj1, People obj2) {
                   Integer p1 = obj1.getid();
                   Integer p2 = obj2.getid();
    
                   if (p1 > p2) {
                       return 1;
                   } else if (p1 < p2){
                       return -1;
                   } else {
                       return 0;
                   }
                }
           }
        }
    

提交回复
热议问题