为什么我的数组比较排序不起作用?



主类:

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).

我做错了吗?

您的EmployeeSortByAnnualSalaryComparator类正在实现您自己的simulator.Comparator接口,但它应该实现java.util.Comparator接口。

Collections.sort方法需要一个实现java.util.Comparator接口的比较器。

相关内容

  • 没有找到相关文章

最新更新