您的位置:首页 > 编程语言 > Java开发

Java案例:Comparable接口用法

2018-02-18 21:42 519 查看
1、Employee


package net.hw.interfaces;

/**
* Created by howard on 2018/1/29.
*/
public class Employee implements Comparable<Employee> {
private String name;
private double salary;

public Employee() {
}

public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

@Override
public int compareTo(Employee other) {
return Double.compare(salary, other.salary);
}
}2、EmployeeSortTest

package net.hw.interfaces;

import java.util.Arrays;

/**
* Created by howard on 2018/1/29.
*/
public class EmployeeSortTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];

staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);

Arrays.sort(staff);

for (Employee e : staff) {
System.out.println("name=" + e.getName() + ", salary=" + e.getSalary());
}
}
}
运行结果如下:


雇员按照薪水升序排列,如果要按薪水降序排列,只须修改Employee类的compareTo方法:


此时,运行程序,结果如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: