Home > Enterprise >  Collections.sort() doesn't work. Problem with implementing the Comparable<> interface
Collections.sort() doesn't work. Problem with implementing the Comparable<> interface

Time:07-08

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

CodePudding user response:

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.

  • Related