collections.sort()无效。实施可比的>界面
有人知道为什么此代码无法正确对员工进行分类?我需要按薪水的薪水数量对它们进行排序。
我认为我已经搞砸了SMTH,因为我将薪水存储在双打中。但是我真的不知道该怎么办。 plz帮助。
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
}
}
Does someone have an idea why this code doesn't sort the employees properly? I need them to be sorted in ascending order by the amount of their salary.
I think I've messed up smth cause I'm storing salaries in doubles. But I really don't know what to do. Plz help.
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于您的
compareTo
函数。 4.2和4.0都作为整数仅4s,因此您的程序不会交换它们。您需要比较双打。我想, 会帮助您。
The problem is with your
compareTo
function. Both 4.2 and 4.0 are just 4s as integers, so your program doesn't swap them.You need to compare doubles. I think, this one will help you.