I have to write an Employee class that has a comparable method that will be used to sort an ArrayList of employees. First it compares the number of years the employee has been working with another employee number of years, if the number of years are the same then it moves on to comparing salary, both conditions should sort in ascending order. My issue is I get an incompatible type error since salary is a double data type, is there anything I can do?
public class Employee implements Comparable<Employee>
{
private String lastName;
private String firstName;
private int years;
private double salary;
public Employee(String lastName, String firstName, int years, double salary)
{
this.lastName=lastName;
this.firstName=firstName;
this.years=years;
this.salary=salary;
}
public void setLastName(String newlastName)
{
lastName=newlastName;
}
public String getLastName()
{
return lastName;
}
public void setFirstName(String newfirstName)
{
firstName=newfirstName;
}
public String getFirstName()
{
return firstName;
}
public void setYears(int newyears)
{
years=newyears;
}
public int getYears()
{
return years;
}
public void setSalary(double newsalary)
{
salary=newsalary;
}
public double getSalary()
{
return salary;
}
public String toString()
{
String s=""+lastName+"-"+firstName+":"+years+":"+salary;
return s;
}
public int compareTo(Employee that)
{
if(this.years != that.getYears())
{
return this.years - that.getYears();
}
else
{
return this.salary - that.getSalary();
}
}
}
I don't like your implementation of
compareTo.I would implement
equalsandhashCodeproperly.If you must implement
Comparable, it should be consistent withequals.I would not have the
Employeeclass implementComparable. You can do that salary/age comparison with a lambda.