Collections.sort() 不起作用。实现 Comparable<> 接口时出现问题



有人知道为什么这段代码不能正确地对员工进行排序吗?我需要它们按照升序排序

我想我搞砸了,因为我用双精度存储工资。但我真的不知道该怎么办。请帮助。

public static void main(String[] args) {
List<Employee> employees = new ArrayList<>(List.of(
new Employee("Steve", 3.1),
new Employee("Mark", 4.2),
new Employee("Oliver", 4)));
System.out.println("Before sorting: " + employees);
employees.sort(Employee::compareTo);
System.out.println("After sorting: " + employees);
}
class Employee implements Comparable<Employee> {
private final String name;
private final double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Employee employee) {
return (int) this.salary - (int) employee.salary;
}
@Override
public String toString() {
return name + " " + Math.round(salary * 100.0) / 100.0; //2 digits after the dot
}
}

Outpute:

这个不行

问题是您的compareTo函数。4.2和4.0都是整数形式的4s,所以你的程序不会交换它们。

你需要比较双精度。我想这张会对你有帮助的。

最新更新