使用 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()。Integer.compare(o1.getAge(), o2.getAge())。TreeSet 依賴 compare 判斷唯一性,若年齡相同會導致元素丟失,需在比較器中加入次級鍵(如姓名、ID)保證唯一。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 精髓,靈活應對各類排序需求。