溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java如何對類的對象進行排序

發布時間:2020-06-17 17:24:19 來源:億速云 閱讀:199 作者:元一 欄目:編程語言

有時我們需要對類按照類中的某一個屬性(或者多個屬性)來對類的對象進行排序,有兩種方法可以實現,一種方法是類實現Comparable<T>接口,然后調用Collections.sort(List)方法進行排序,另一種方法是類不實現Comparable<T>接口,而在排序時使用Collections.sort(List, Comparator<T>)方法,并實現其中的Comparator<T>接口。

先創建一個簡單的學生類:

public class Student {
    
    private String name;
    
    private int age;
 
    public Student() {}
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

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

public class Student implements Comparable<Student>{
 
    private String name;
 
    private int age;
 
    public Student() {}
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    /**
     * 將對象按姓名字典序升序排序
     * @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 +
                '}';
    }
}

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

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());
        }
    }
 
}

總結

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

以上就是java中實現對類的對象進行排序的詳細內容,更多請關注億速云其它相關文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女