【发布时间】:2016-04-24 20:10:19
【问题描述】:
我有一个抽象类:
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 对象感到困惑。
【问题讨论】:
-
请展示您到目前为止所做的尝试。
-
你不能在原语上使用 compareTo
[int].compareTo([int])不起作用。如果您想要这样的功能,请使用Integer包装类。 -
已更正。谢谢。
-
嗨,安迪,感谢您的意见。只是在 Comparable vs Comparator 上阅读自然排序。每天学习新东西!
标签: java sorting generics collections comparable