其他分享
首页 > 其他分享> > 浅析 Comparable 和 Comparator

浅析 Comparable 和 Comparator

作者:互联网

相同点

不同点

示例

示例代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("lucy",21);
        students[1] = new Student("tom",23);
        students[2] = new Student("anna",25);
        // 使用默认的排序方式:以姓名排序
        // 由于实现了Comparable接口,所以可以直接使用Arrays.sort排序
        // Arrays.sort使用Comparable实现的内部比较器
        Arrays.sort(students);
        System.out.println("使用Comparable排序");
        for (Student student : students) {
            System.out.println(student);
        }

        System.out.println("===========================");
        // 使用扩展的排序方式:以年龄升序排序
        // 为Arrays.sort传入一个外部实现的Comparator比较器
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return Integer.compare(s1.age, s2.age);
            }
        });

        System.out.println("使用Comparator排序");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

class Student implements Comparable<Student> {
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }

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

示例结果

在这里插入图片描述

标签:Comparable,name,Comparator,浅析,Student,排序,public
来源: https://www.cnblogs.com/Acx7/p/15841579.html