首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java Comparator 介面實現按年齡升序排序詳解

     編輯:程式設計疑難解答

代碼場景

使用 TreeSet 存儲學生對象,通過自定義 Comparator 實現按年齡從小到大排序:

class AgeAscComparator implements Comparator {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getAge() - o2.getAge();
    }
}

原理深度解析

  • 返回值規則:
    • 負數:o1 排在 o2 前面(升序)
    • 零:視為相等
    • 正數:o1 排在 o2 後面
  • o1.getAge() - o2.getAge() 正是利用整數減法的正負特性實現升序。
  • 若需降序,只需交換位置:o2.getAge() - o1.getAge()。

注意事項

  1. 整數溢出風險:年齡差極大時可能溢出,生產環境建議用 Integer.compare(o1.getAge(), o2.getAge())。
  2. TreeSet 依賴 compare 判斷唯一性,若年齡相同會導致元素丟失,需在比較器中加入次級鍵(如姓名、ID)保證唯一。
  3. Java 8+ 可用 Lambda 簡寫:Comparator.comparingInt(Student::getAge)。

運行結果示例

[Student{name='李四', age=1}, Student{name='王五', age=2}, Student{name='張三', age=3}, Student{name='田七', age=4}, Student{name='陳六', age=5}]

掌握 Comparator 精髓,靈活應對各類排序需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved