1. 程式人生 > >Comparable介面實現集合的排序

Comparable介面實現集合的排序

1.讓需要排序的物件實現Comparable介面,並重寫compareTo方法

public class Student implements Comparable<Student> {  //泛型為需要排序的物件    
private int age;
  
private String name; private int score; public int getAge() { return age; } public void
setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; }
public Student(int age, String name, int score) { super(); this.age = age; this.name = name; this.score = score; }
@Override public int compareTo(Student other) {    //引數為需要排序的物件 return score-other.getScore();  //表示通過分數score欄位進行排序 } }

2.構造需要排序的物件的集合,並呼叫Collections.sort()方法對集合中元素進行排序:

public class CompareTest {

    public static void main(String[] args) {
        Student s1 = new Student(16, "aa", 44);
        Student s2 = new Student(18, "bb", 88);
        Student s3 = new Student(17, "cc", 99);
        Student s4 = new Student(19, "dd", 66);

        List<Student> students = Arrays.asList(s1, s2, s3, s4);

        Collections.sort(students);  //對students按score欄位進行排序  

        for (Student student : students) {
            System.out.println(student.getScore());
        }
    }
}

注意:使用 Collections.sort(students);方法對集合物件進行排序時,集合中的物件必須實現Comparable介面,否則報錯