我必须编写一个Employee类,它有一个可比较的方法,用于对员工的ArrayList进行排序。首先比较雇员的工作年数和另一个雇员的工作年数,如果年数相同,则继续比较工资,两个条件都应按升序排序。我的问题是我得到一个不兼容的类型错误,因为工资是双数据类型,有什么我能做的吗?
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();
}
}
}
this.salary - that.getSalary()
返回double
,而compareTo()
函数需要返回int
。一般来说,Java不喜欢隐式地将double
转换为int
,因为这会导致信息丢失(我认为错误说明了"有损转换")。
实现使用double
变量比较两个对象的compareTo()
的一种方法是根据比较手动返回-1、0或1:
if (this.salary < that.getSalary())
return -1;
else if (this.salary > that.getSalary())
return 1;
return 0;
我不喜欢你对compareTo
的实现。
我会正确地实现equals
和hashCode
。
如果你必须实现Comparable
,它应该与equals
一致。
我不会让Employee
类实现Comparable
。您可以使用lambda进行工资/年龄比较。
遗憾的是,没有办法允许compareTo
方法返回int
以外的东西。幸运的是,有一个解决方法!
Comparables不需要返回两个输入之间的确切差异,只需要指示哪个输入更大。
。您不需要返回1
、0
和-1
以外的任何值。
因此,Math.signum()
可以来拯救!
Math.signum(double d)
返回d
的符号,如果是d == 0
则返回0。
更多关于Math.signum()
的信息请访问geeksforgeeks: https://www.geeksforgeeks.org/java-signum-method-examples/
也有一个用于整数的signum版本:Integer.signum(int i)
在你的代码中应该是这样的:
public int compareTo(Employee that)
{
if(this.years != that.getYears())
{
return Integer.signum(this.years - that.getYears());
}
else
{
return (int) Math.signum(this.salary - that.getSalary());
}
}
注意,我们必须将Math.signum(this.salary - that.getSalary())
转换为int
,因为它返回double