How to use Comparator in Java to sort

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

    You want to implement Comparable, not Comparator. You need to implement the compareTo method. You're close though. Comparator is a "3rd party" comparison routine. Comparable is that this object can be compared with another.

    public int compareTo(Object obj1) {
      People that = (People)obj1;
      Integer p1 = this.getId();
      Integer p2 = that.getid();
    
      if (p1 > p2 ){
       return 1;
      }
      else if (p1 < p2){
       return -1;
      }
      else
       return 0;
     }
    

    Note, you may want to check for nulls in here for getId..just in case.

提交回复
热议问题