Nicole
Nicole

Reputation: 53

adding comparable interface and adding a compareTo() method

I'm having a bit of trouble adding the two noted above. I have two classes. Employee and Company.

The employee class holds some information about the employees, instance variables including their name, dates, numOfSales etc etc. And also some methods such as setName, getName and so on.

The Company class creates an empty List. It then has a method which reads the list of employees from a text file - which is then how the list gets filled up.

What I need to do is: sort the list by their numOfSales. I first of all need to modify the employee class so that it implements the Comparable interface.

public class Employee implements Comparable<Company>

I'm not sure if company or employee should go in there ^ <> ? But when I try either, I get the error message that 'Employee is not abstract and does not override abstract method CompareTo in java.lang.Comparable' What am I doing wrong here? I must not changed any of the classes, they must not be changed to abstract or anything and I must not add any new ones.

I then need to write a compareTo() method, I take it in the employee class? that will allow the employees to be sorted in ascending order of the value stored by their numOfSales instance variable.

Upvotes: 1

Views: 891

Answers (2)

Mureinik
Mureinik

Reputation: 311393

An Employee should be comparable to other Employees, so it's Comparable<Employee>. You then need to implement the compareTo method, as the error message says:

public class Employee implements Comparable<Employee> {
    private int numOfSales;
    // other data members

    // Constructors, getters, setters, etc

    @Override
    public int compareTo(Employee e) {
        return Integer.compare(numOfSales, e.numOfSales);
    }
}

Upvotes: 2

Ackdari
Ackdari

Reputation: 3498

If you have somekind of List<Employee> the you can use the static method Collections.sort() to sort it without implementing the Comparable interface on the Employee class. You can simply use the variant of the sort function that accepts an Comparator object which will be used to compare two instances of the Employee class.

And you don't even need to implement one on your own. You can simply use Comparator.comparingInt​(e -> e.numOfSales) to create the correct Comparator to sort your list.

So

Collections.sort(employees, Comparator.comparingInt​(e -> e.numOfSales));

would be sufficent to sort your employee list.

Upvotes: 2

Related Questions