Comparable接口实现sort排序方法

在 Java 程序设计语言中, 接口不是类,而是对类的一组需求描述,这些类要遵从接口描
述的统一格式进行定义。
我们经常听到服务提供商这样说:“ 如果类遵从某个特定接口,那么就履行这项服务'
下面给出一个具体的示例。Arrays 类中的 sort 方法承诺可以对对象数组进行排序, 但要求满
足下列前提: 对象所属的类必须实现了 Comparable 接口。

下面是 Comparable 接口的代码:

public interface Comparable{
    int compareTo(Object other);
}

这就是说, 任何实现 Comparable 接口的类都需要包含 compareTo 方法, 并且这个方法的参
数必须是一个 Object 对象, 返回一个整型数值。

Employee.java
public class Employee implements Comparable {
    private String name;
    private double salary;
    public String getName() {
        return name;
    }
    public double getSalary() {
        return salary;
    }

    public Employee (String name, double salary){
        this.name = name;
        this.salary = salary;
        this.height = height;
    }
    public void raiseSalary(double byPercent){
        double raise = salary*byPercent/100;
        salary+=raise;
    }
    public int compareTo(Employee other){
        return Double.compare(salary,other.salary);
    }
}
EmployeeSortTest.java
public class EmployeeSortTest {
    public static void main(String[] args) {
        Employee[] staff =  new Employee[4];
        staff[0] = new Employee("张三",35000);
        staff[1] = new Employee("李四",75000);
        staff[2] = new Employee("老八",38000);
        staff[3] = new Employee("l",38000);

        Arrays.sort(staff);
        for(Employee e :staff)
            System.out.println("name=" +e.getName()+",salary="+e.getSalary());
    }
}

Comparable接口实现sort排序方法_第1张图片

 加入age字段

public class EmployeeSortTest {
    public static void main(String[] args) {
        Employee[] staff =  new Employee[4];
        staff[0] = new Employee("张三",35000,22);
        staff[1] = new Employee("李四",20000,32);
        staff[2] = new Employee("老八",38000,234);
        staff[3] = new Employee("l",38000,23);

        Arrays.sort(staff,((a1,a2)->{
            if(a1.getAge()>a2.getAge()){
                return 1;
            }else if(a1.getAge()Comparable接口实现sort排序方法_第2张图片

简化:

public class EmployeeSortTest {
    public static void main(String[] args) {
        Employee[] staff =  new Employee[4];
        staff[0] = new Employee("张三",35000,22);
        staff[1] = new Employee("李四",20000,32);
        staff[2] = new Employee("老八",38000,234);
        staff[3] = new Employee("l",38000,23);

        Arrays.sort(staff,(Comparator.comparingInt(Employee::getAge)));
//        Arrays.sort(staff, Comparator.comparingInt(Employee::getHeight));
        for(Employee e :staff)
            System.out.println("name=" +e.getName()+",salary="+e.getSalary()+",age="+e.getAge());
    }
}

 

你可能感兴趣的:(数据结构)