【发布时间】:2021-11-10 00:24:34
【问题描述】:
主类:
package simulator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import rh.Employee;
import rh.SalaryIncrease;
import rh.SalaryIncreaseMock;
import rh.increase.GradualSalaryIncrease;
import rh.increase.StandardSalaryIncrease;
public class Simulator {
public static void main(String[] args) {
new Simulator();
}
private List<Employee> ListOfEmployees;
public Simulator() {
System.out.println("STRATEGY PATTERN et POLYMORPHISME ******************************");
this.seedData();
this.printData("Employés avant les augmentations");
this.applySalaryIncrease();
this.printData("Employés après les augmentations");
}
private void seedData() {
this.ListOfEmployees = new ArrayList<Employee>();
this.ListOfEmployees.add(new Employee("Jean", 50000));
this.ListOfEmployees.add(new Employee("Françis", 50000));
this.ListOfEmployees.add(new Employee("Jeanne", 10000));
this.ListOfEmployees.add(new Employee("Kevin", 85000));
this.ListOfEmployees.add(new Employee("Bernard", 10000));
this.ListOfEmployees.add(new Employee("James", 35000));
Collections.sort(this.ListOfEmployees, new EmployeeSortByAnnualSalaryComparator());
this.printData("Employés classée en ordre alphabétique");
this.printData("Employés classée en ordre croisant de salaire");
}
private void applySalaryIncrease() {
int counter = 0;
for(Employee anEmployee:this.ListOfEmployees) {
SalaryIncrease increase;
if(counter % 2 == 0) {
increase = new StandardSalaryIncrease(10);
}
else {
increase = new GradualSalaryIncrease(10);
}
anEmployee.applySalaryIncrease(increase);
counter++;
}
}
private void printData(String title) {
System.out.println();
System.out.println(title);
System.out.println("=======================================================");
for(Employee anEmployee:this.ListOfEmployees) {
System.out.println(anEmployee.toString());
}
}
}
我的比较器界面
package simulator;
public interface Comparator<T> {
int compare(T firstElement,T secondElement);
}
比较器实现
package simulator;
import rh.Employee;
public class EmployeeSortByAnnualSalaryComparator implements Comparator<Employee>{
public EmployeeSortByAnnualSalaryComparator(){
}
@Override
public int compare(Employee anEmployeeSalary, Employee aSecondEmployeeSalary) {
if(anEmployeeSalary.getSalary() < aSecondEmployeeSalary.getSalary()) {
return -1;
}
if(anEmployeeSalary.getSalary() == aSecondEmployeeSalary.getSalary()) {
return 0;
}
else {
return 1;
}
}
}
界面应该和t一样。
当我尝试对名称或数字进行排序时,我在排序时看到此错误,表明我的类型错误:
The method sort(List<T>, >Comparator<? super T>) in the type Collections is not applicable for the arguments>(List<Employee>, EmployeeSortByAnnual Salary Comparator).
我做错了吗?
【问题讨论】:
-
请以可复制粘贴的方式粘贴分隔的类进行测试。
-
Collections.sort(this.ListOfEmployees, Comparator.comparing(Employee::getSalary)); -
友情反馈:下次能否指出错误信息属于哪一步。在这种情况下,这是一个编译错误。这将有助于了解触发错误的问题类型。
标签: java eclipse sorting comparator junit5