java對象排序


一、前言

有時我們需要對類按照類中的某一個屬性(或者多個屬性)來對類的對象進行排序,有兩種方法可以實現,

一種方法是類實現Comparable<T>接口,然后調用Collections.sort(List)方法進行排序,

另一種方法是類不實現Comparable<T>接口,而在排序時使用Collections.sort(List, Comparator<T>)方法,並實現其中的Comparator<T>接口。

二、排序實現

假設有一個學生類Student,包含兩個屬性:姓名name,年齡age,如下:

public class Student {
    
    private String name;
    
    private int age;

    ....get.set
}

1、通過類實現Comparable<T>接口進行排序

public class Student implements Comparable<Student>{

    private String name;

    private int age;

    ...get.set

    /**
     * 將對象按姓名字典序升序排序
     * @param o
     * @return
     */
    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.getName()); }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

測試

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Client {

    public static void main(String[] args){
        List<Student> students = new ArrayList<>();
        students.add(new Student("a", 18));
        students.add(new Student("c", 19));
        students.add(new Student("b", 20));

        Collections.sort(students);
        for(Student student:students){
            System.out.println(student.toString());
        }
    }

}

輸出

Student{name='a', age=18}
Student{name='b', age=20}
Student{name='c', age=19}

2、通過在Collections.sort()方法中實現Comparable<T>接口來實現排序

實體類不實現Comparable接口

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Client {

    public static void main(String[] args){
        List<Student> students = new ArrayList<>();
        students.add(new Student("a", 18));
        students.add(new Student("c", 19));
        students.add(new Student("b", 20));

        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1); } });
        for(Student student:students){
            System.out.println(student.toString());
        }
    }

}

結果:

Student{name='b', age=20}
Student{name='c', age=19}
Student{name='a', age=18}

可以看到學生按年齡從大到小排序輸出。使用這種方法時要注意在比較函數compare的返回值中要包含0(年齡相等),不然可能會出現Comparison method violates its general contract!異常。

三、總結

無論使用上面的哪一種方法,對對象排序的核心是實現比較函數,其中第二種方法比第一種方法更加靈活。

 

 

摘自:https://www.cnblogs.com/sench/p/8889435.html


免責聲明!

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



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