I have an interface (say Employee) which has 2 classes that implements it (say Assistant and Manager). I also have an interface which has a method that returns a list of the first interface type (say EmployeeLogic interface which returns List. There are two classes implementing this interface (say AssistantLogic and ManagerLogic). In these two classes, the List contains only Assistants (in the AssitantLogic) and only Manager (in the ManagerLogic).
The problem is that I want to sort these two lists based on the methods that exist only in the subclasses. How do I write such a comparator?
Probably the code is better understandable:
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;
}
}
Is there a way to write such a comparator?
I know a workaround (see bellow) but is the above thing possible with only one list?
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;
}
}
If I understand you correctly, your problem isn’t about trying to sort a mix of
Assistants andManagers, but about the fact that you can only sort either a list ofAssistants or a list ofManagers, but you want to return a list ofEmployees.In that case, one thing you could do is have
getEmployees()return aList<? extends Employee>.If that is not an option, and if you don’t intend for the returned list to be modified, you can do
return Collections.unmodifiableList(managers).If you intend the returned list to be modifiable, then your solution is the cleanest way to do it.