在日常開發中,很多時候都需要對一些資料進行排序的操作。然而那些資料一般都是放在一個集合中如:Map ,Set ,List 等集合中。他們都提共了一個排序方法 sort(),要對資料排序直接使用這個方法就行,但是要保證集合中的對象是 可比較的。
怎麼讓一個對象是 可比較的,那就需要該對象實作 Comparable 接口啦。 然後**重寫裡面的
compareTo()**方法。我們可以看到Java中很多類都是實作類這個接口的 如:Integer,Long 等等。。。
一、小demo
假設我們有一個學生類,預設需要按學生的年齡字段 age 進行排序 代碼如下:
public class Student implements Comparable<Student> {
private int id;
private int age;
private String name;
public Student(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Override
public int compareTo(Student o) {
//降序
//return o.age - this.age;
//升序
return this.age - o.age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
如果說是先按age排序 age相同再按id排序多條件這中情況的話,可以這樣處理:
if (o1.age == o2.age){
reture o1.id 小于 o2.id;
}else{
reture o1.age 小于 o2.age;
}
這裡說一下重寫的
public int compareTo(Student o){}
這個方法,它傳回三種 int 類型的值: 負整數,零 ,正整數。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL1YjNxMzN1EjM0EDOwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
二、測試:
public static void main(String args[]){
List<Student> list = new ArrayList<>();
list.add(new Student(1,25,"關羽"));
list.add(new Student(2,21,"張飛"));
list.add(new Student(3,18,"劉備"));
list.add(new Student(4,32,"袁紹"));
list.add(new Student(5,36,"趙雲"));
list.add(new Student(6,16,"曹操"));
System.out.println("排序前:");
for (Student student : list) {
System.out.println(student.toString());
}
//使用預設排序
Collections.sort(list);
System.out.println("預設排序後:");
for (Student student : list) {
System.out.println(student.toString());
}
}
排序前:
Student{id=1, age=25, name='關羽'}
Student{id=2, age=21, name='張飛'}
Student{id=3, age=18, name='劉備'}
Student{id=4, age=32, name='袁紹'}
Student{id=5, age=36, name='趙雲'}
Student{id=6, age=16, name='曹操'}
預設排序後:
Student{id=6, age=16, name='曹操'}
Student{id=3, age=18, name='劉備'}
Student{id=2, age=21, name='張飛'}
Student{id=1, age=25, name='關羽'}
Student{id=4, age=32, name='袁紹'}
Student{id=5, age=36, name='趙雲'}
小結:
實作了Comparable接口的類都可以用sort方法進行排序,預設的排序方法是升序;如果想進行降序排序,隻需把Collections.reverseOrder作為第二個參數傳給sort方法。