通过枚举+Comparable接口实现子类优先级排序
在实现接口Comparable
的compareTo()
方法后,可以通过使用Arrays.sort()
方法来进行排序。但我们日常生活中,对象是复杂的,尤其是在面向对象思想中我们更需要面向现实生活的具体场景,因此写了一个小demo,来实现生活中我们的排序问题。
在一个Employee
(雇员)类中,我们只需要比较它们的Salary(薪水)就行了,但是我们从中还扩展出了Manager
(经理)、Secretary
(秘书)等子类,这时候我们在归类比较的时候就需要按类别比较各自的优先级,同级别下然后再比较各自的薪水,不同优先级,以优先级高的先输出,再按薪水从大到小输出。
Employee(雇员):
package com.pixcer;
/**
* <b>雇员<br/>
*
* @author gu-ppy
* @Package com.pixcer
* @date 20/12/08 13:15
*/
public class Employee implements Comparable<Employee>{
private int id;
private String name;
/**
* <b>薪水
*/
private double salary;
public Employee() {
}
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public double getSalary() {
return salary;
}
@Override
public int compareTo(Employee o) {
if (this.getPriority().getPCode()!=o.getPriority().getPCode())
return o.getPriority().getPCode()-this.getPriority().getPCode();
//从大到小排列
return Double.compare(o.salary,this.salary);
}
/**
* 获取多个类的优先级
* @description:
* @return: int
*/
public Priority getPriority() {
return Priority.EMPLOYEE;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
Manager(经理):
package com.pixcer;
/**
* <b>经理<br/>
*
* @author gu-ppy
* @Package com.pixcer
* @date 20/12/08 14:34
*/
public class Manager extends Employee{
private double bonus; //奖金
public Manager(int id, String name, double salary, double bonus) {
super(id, name, salary);
this.bonus = bonus;
}
@Override
public Priority getPriority() {
return Priority.MANAGER;
}
@Override
public String toString() {
return super.toString()+"Manager[bonus="+bonus+"]";
}
}
Secretary(秘书):
package com.pixcer;
/**
* <b>秘书<br/>
*
* @author gu-ppy
* @Package com.pixcer
* @date 20/12/08 14:47
*/
public class Secretary extends Employee{
public Secretary(int id, String name, double salary) {
super(id, name, salary);
}
@Override
public Priority getPriority() {
return Priority.SECRETARY;
}
@Override
public String toString() {
return super.toString()+"Secretary[]";
}
}
Priority(优先级):
package com.pixcer;
/**
* <h1>权限枚举</h1>
* <hr/>
*
* @author gu-ppy
* @package com.pixcer
* @date 2020/12/08 16:56
*/
public enum Priority {
/**
* 初始Employee,Manager权限数值
* {@code pCode}越大其优先级越高,排序越靠前
*/
EMPLOYEE(1000),MANAGER(3000),SECRETARY(2000);
private final int pCode;
Priority(int code){
this.pCode=code;
}
public int getPCode() {
return pCode;
}
}
最终的测试:
public static void main(String[] args) {
Employee[] employee = {
new Employee(1,"ppy1",10000),
new Employee(2,"ppy2",8000),
new Manager(3,"sn",5000,40000),
new Employee(4,"pdd",6000),
new Secretary(5,"ddd",7000),
new Manager(6,"sn",10000,50000),
};
for (Employee employee1 : employee) {
System.out.println(employee1);
}
//排序
Arrays.sort(employee);
System.out.println("排序后:");
for (Employee employee1 : employee) {
System.out.println(employee1);
}
}