collections.sort()无效。实施可比的>界面

发布于 2025-02-13 18:49:39 字数 1263 浏览 0 评论 0原文

有人知道为什么此代码无法正确对员工进行分类?我需要按薪水的薪水数量对它们进行排序。

我认为我已经搞砸了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
    }
}

oftute:

这不行

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
    }
}

Outpute:

This doesn't work as well

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长不大的小祸害 2025-02-20 18:49:40

问题在于您的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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文