但是,您可以具有多个实现该接口的类,并且可以在希望对Employee列表进行排序时选择相关的Comparator<Employee>实现.I am developing a small application , I have an "Employee" class with methods and corresponding attributes (name , salary , date .. ) and another class that is a list of employees , which I use an arraylist to store employees and different methods , such as adding employee , delete employee .Now I 'm trying to sort employees by alphabetical order and date of hire (lowest to highest).But I have a little problem, I can not use the method compare more than 2 times, I have been researching and not whether it could overload the method compare to sort employees by name and date .thanks. public class Employee { private String name; private GregorianCalendar dateHire; public GregorianCalendar getDateHire() { return dateHire; } public void setDateHire(GregorianCalendar dateHire) { this.dateHire = dateHire; }public getName() { return name;}public setName (String name) { this.name = name;} }//------------------------------------------------------ public class listEmployee implements Comparator <Employee> { ArrayList<Employee> Employees = new ArrayList<>(); @Override public int compare(Employee e1, Employee e2) { if (e1.getName() != e2.getName()) { return 1; } else { return -1; } }// now , when I call this function in the parent class , if you sort the names , now when I try//to sort dates , not let me use the method compare more than twice public void sortAlphabetical() { Collections.sort(trabajadores,Employee.StuNameComparator); } //I was looking online and found these options, but not as a call in the main class public static Comparator <Employee > sortDate = new Comparator<Employee >() { @Override public int compare (Employee s1, Employee s2) { GregorianCalendar empTemporal = s1.getDateHire(); GregorianCalendar emTemporal2 = s2.getDateHire(); return empTemporal.compareTo(emTemporal2); } }; public static Comparator <Employee> StuNameComparator = new Comparator<Employee >() { @Override public int compare(Employee s1, Employee s2) { String EmployeName1 = s1.getName().toUpperCase(); String EmployeName2 = s2.getName().toUpperCase(); //ascending order return EmployeName1.compareTo( EmployeName2); //descending order //return StudentName2.compareTo(StudentName1); }}; } 解决方案 You can't overload the compare method of the Comparator<Employee> interface, since there is just one signature to that method - int compare(Employee s1, Employee s2).However, you can have multiple classes that implement that interface, and you can choose the relevant Comparator<Employee> implementation whenever you wish to sort your Employee list. 这篇关于作为重载的方法比较Comparator接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-03 05:44