Discussion of Activity 5.5 - Using an interface

Sample solutions

  1. Comparing Employee objects by salary:

    The class header must be modified as follows:

    public class Employee implements Comparable<Employee>
    

    An example method implementation is as follows:

    public int compareTo(Employee emp)
    {
        if (salary > emp.salary)
        {
           return 1;
        }
        if (salary < emp.salary)
        {
           return -1;
        }
    
        return 0;
    }
    
  2. In fact there is a more elegant way of doing this that returns a more useful value, and that is simply to find the difference between the two employee salaries like this:

    public int compareTo(Employee emp)
    {
        return this.salary - emp.salary;
    }
    

    Not only does this method return a useful value (the difference between the employee's salaries), but it is easy to reverse sorting using this approach:

    public int compareTo(Employee emp)
    {
        return emp.salary - this.salary;
    }
    

  3. The class header cannot be changed if we are to use Arrays.sort as this method requires the items in the array to implement Comparable for their own type.

    A possible method implementation is now as follows:

    public int compareTo(Employee emp)
    {   
       return emp.name.compareTo(name);
    }
    

    Here we make use of the fact that the String class already has a suitable compareTo method defined (this compareTo method accepts a String argument only).