一、用法
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é)
- Comparable與Comparator都可以實(shí)現(xiàn)排序,都是接口類型;
- Comparable放在實(shí)體類中,定意一種排序,當(dāng)排序需求變更,無(wú)法滿足;
- Comparator 可以理解為對(duì)Comparable的擴(kuò)展,可以對(duì)同一個(gè)類定義多個(gè)排序規(guī)則,使用更加靈活。