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接口,否則報錯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM