我有一个接口(比如Employee),它有2个实现它的类(比如Assistant和Manager)。我还有一个接口,它有一个返回第一个接口类型列表的方法(比如返回 List 的 EmployeeLogic 接口。有两个类实现了这个接口(比如 AssistantLogic 和 ManagerLogic)。在这两个类中,List 只包含助手(在 AssitantLogic 中)并且只有 Manager(在 ManagerLogic 中)。
问题是我想根据仅存在于子类中的方法对这两个列表进行排序。我该如何编写这样的比较器?
可能代码更容易理解:
public interface Employee {
public int employeeMethod();
}
public class Manager implements Employee {
public int employeeMehod(){//[...]}
public int managerMethod(){//[...]}
}
public class Assistant implements Employee {
public int employeeMehod(){//[...]}
public String assistantMehod(){//[...]}
}
public interface EmployeeLogic() {
public List<Employee> getEmployees();
}
public class ManagerLogic implements EmployeeLogic {
public List<Employee> getEmployees() {
List<Employee> employees = [...] //or List<? extends Employee> ?
[...]
Collections.sort(employees, new Comparator<Manager>() {
@Override
public int compare(Manager o1, Manager o2) {
return o1.managerMethod().compareTo(o2.managerMethod());
}
});
return employees;
}
}
public class AssistantLogic implements EmployeeLogic {
public List<Employee> getEmployees() {
List<Employee> employees = [...] //or List<? extends Employee> ?
[...]
Collections.sort(employees, new Comparator<Assistant>() {
@Override
public int compare(Assistant o1, Assistant o2) {
return o1.assistantMehod().compareTo(o2.assistantMehod());
}
});
return employees;
}
}
有没有办法写这样一个比较器?
我知道一种解决方法(见下文),但上述事情是否可能只用一个列表?
public class ManagerLogic implements EmployeeLogic {
public List<Employee> getEmployees() {
List<Manager> managers = new ArrayList<Manager>()
[...]
Collections.sort(managers, new Comparator<Manager>() {
@Override
public int compare(Manager o1, Manager o2) {
return o1.managerMethod().compareTo(o2.managerMethod());
}
});
List<Employee> employees = new ArrayList<Employee>();
employees.addAll(managers);
return employees;
}
}