当两种类型的数据不同时,如何使用具有if条件的可比方法?



我必须编写一个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的实现。

我会正确地实现equalshashCode

如果你必须实现Comparable,它应该与equals一致。

我不会让Employee类实现Comparable。您可以使用lambda进行工资/年龄比较。

遗憾的是,没有办法允许compareTo方法返回int以外的东西。幸运的是,有一个解决方法!

Comparables不需要返回两个输入之间的确切差异,只需要指示哪个输入更大。

。您不需要返回10-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

最新更新