Java 集合排序Comparable與Comparator

一、用法

1. Comparable用法

源碼如下:

public interface Comparable<T> {
   //a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 
   負(fù)數(shù)、0、正數(shù) 分別代表該對(duì)象 小于、等于 大于 比較對(duì)象
   public int compareTo(T o);
}

創(chuàng)建一個(gè)學(xué)生類如下:

public class StudentModel implements Comparable<StudentModel> {
  private int num;//編號(hào)
  private int age;//年齡
  private String name;//姓名

  public StudentModel(int num, int age, String name) {
      this.num = num;
      this.age = age;
      this.name = name;
  }

  //get set方法
  ...
  //將自身與o做對(duì)比 自身在前將是升序排序 反之降序
  @Override
  public int compareTo(StudentModel o) {
      return num -o.num ;
  }

  @Override
  public String toString() {
      return name+",num="+num+",age="+age;
  }
}

測(cè)試代碼:

      List<StudentModel> list = new ArrayList<>();
      list.add(new StudentModel(1,10,"張三"));
      list.add(new StudentModel(5,9,"李四"));
      list.add(new StudentModel(3,12,"王五"));
      
      Collections.sort(list);
      for (StudentModel item:list) {
          System.out.println(item);
      }

測(cè)試結(jié)果:根據(jù)編號(hào)升序排序

張三,num=1,age=10
王五,num=3,age=12
李四,num=5,age=9

2. Comparator用法

如果需求變更,希望按照學(xué)生age排序,則上述代碼需要改動(dòng),這時(shí)候我們可以使用Comparator來(lái)滿足需求,測(cè)試代碼如下:

    Collections.sort(list, new Comparator<StudentModel>() {
          @Override
          public int compare(StudentModel o1, StudentModel o2) {
              return o1.getAge()-o2.getAge();
          }
      });

      for (StudentModel item:list) {
          System.out.println(item);
      }

測(cè)試結(jié)果如下:

李四,num=5,age=9
張三,num=1,age=10
王五,num=3,age=12

二、總結(jié)

  1. Comparable與Comparator都可以實(shí)現(xiàn)排序,都是接口類型;
  2. Comparable放在實(shí)體類中,定意一種排序,當(dāng)排序需求變更,無(wú)法滿足;
  3. Comparator 可以理解為對(duì)Comparable的擴(kuò)展,可以對(duì)同一個(gè)類定義多個(gè)排序規(guī)則,使用更加靈活。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容