我有一个抽象类:
public abstract class Employee implements Comparable<Employee>{
public Double getSalary();
@Override
public Double compareTo(final Employee employee2) {
}
}
扩展此抽象类的两个类:
public class Manager {
public Double getSalary(){}
}
public class Chef{
public Double getSalary(){}
}
我想对其进行排序,使列表中的所有 Chef 对象都位于前面,然后在所有 Chef 对象之后,我希望 Manager 对象按降序排序,首先是薪水最高的对象。换句话说,对于 Chef 对象,我只想将它们推到列表的前面,而不是其他。对于 Manager 对象,我希望它们按薪水排序,并放在 Chef 对象之后的列表末尾。
例如
Manager manager1 = new Manager(40000);
Manager manager2 = new Manager(50000);
Manager manager3 = new Manager(60000);
Chef chef1 = new Chef(25000);
Chef chef2 = new Chef(25500);
Chef chef3 = new Chef(28000);
Chef chef4 = new Chef(29000);
List<Employee> employees = new ArrayList<Employee>();
employees.add(manager3);
employees.add(manager1);
employees.add(chef1);
employees.add(chef3);
employees.add(manager2);
employees.add(chef4);
employees.add(chef2);
对列表中的元素进行排序后可能如下所示:
0. chef1 = 25000 // Chef objects pushed to front but not sorted by salary
1. chef3 = 28000
2. chef4 = 29000
3. chef2 = 25500
4. manager3 = 60000 // Manager objects pushed to the back and sorted by salary
5. manager2 = 50000
6. manager1 = 40000
我的compareTo方法:
@Override
public int compareTo(final Employee employee2) {
if (this instanceof Manager|| employee2instanceof Manager) {
return employee2.getSalary().compareTo(this.getSalary());
}
return -1;
}
但是,这会将 Manager 对象带到前面。我对如何在此compareTo 方法中使用Chef 对象感到困惑。
最佳答案
您的案例听起来像是创建 Comparator
的案例比实现 Comparable
更合适:后者专门用于对类实例的自然顺序进行建模。
例如,Integer implements Comparable<Integer>
:整数有一个非常明显的自然顺序。
您的案例听起来更像是您想要如何对它们进行排序的一次性案例,例如在特定报告中呈现。
此外,我认为当父类需要了解其子类时,这是一种代码味道。没有什么可以阻止新子类的创建;不需要更新Employee
处理这个事实。
从一种转换为另一种很容易:而不是添加 int compare(Employee that)
方法Employee
,您在比较器中实现一个方法:
class ChefsAndManagersComparator implements Comparator<Employee> {
@Override
public int compare(Employee employee1, Employee employee2) {
// The logic from any of the other answers,
// just replacing "this" references with "employee1"
}
}
关于java - 如何对具有实现相同接口(interface)的不同对象的列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828369/