简体   繁体   English

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

[英]How do I use comparable method with if conditions when the two types of data are different?

I have to write an Employee class that has a comparable method that will be used to sort an ArrayList of employees.我必须编写一个 Employee 类,该类具有可用于对员工的 ArrayList 进行排序的类似方法。 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();
        }
    }
}

this.salary - that.getSalary() results in a double , but the compareTo() function needs to return an int . this.salary - that.getSalary()产生一个double ,但compareTo()函数需要返回一个int In general, Java doesn't like to implicitly convert a double to an int because that results in a loss of information (I presume the error said something about a "lossy conversion").一般来说,Java 不喜欢将double隐式转换为int ,因为这会导致信息丢失(我认为错误说明了“有损转换”)。

One way to implement a compareTo() that uses double variables to compare two objects is to manually return -1, 0, or 1 depending on the comparison:实现使用double变量比较两个对象的compareTo()的一种方法是根据比较手动返回 -1、0 或 1:

if (this.salary < that.getSalary())
    return -1;
else if (this.salary > that.getSalary())
    return 1;
return 0;

I don't like your implementation of compareTo .我不喜欢您的compareTo实现。

I would implement equals and hashCode properly.我会正确实现equalshashCode

If you must implement Comparable , it should be consistent with equals .如果你必须实现Comparable ,它应该与equals一致。

I would not have the Employee class implement Comparable .我不会让Employee类实现Comparable You can do that salary/age comparison with a lambda.您可以使用 lambda 进行薪水/年龄比较。

Sadly, there is no way to allow the compareTo method to return something other than an int .可悲的是,没有办法允许compareTo方法返回int以外的东西。 Luckily, there is a workaround!幸运的是,有一个解决方法!

Comparables do not need to return the exact difference between the two inputs, just an indication as to which one is larger. Comparables 不需要返回两个输入之间的确切差异,只需指示哪个更大。

ie you don't need to return anything other than 1 , 0 , and -1 .即您不需要返回除10-1以外的任何内容。

Therefore, Math.signum() can come to the rescue!因此, Math.signum()可以来救援!

Math.signum(double d) returns the sign of d , or 0 if d == 0 . Math.signum(double d)返回d的符号,如果d == 0

More info on Math.signum() at geeksforgeeks: https://www.geeksforgeeks.org/java-signum-method-examples/更多关于 geeksforgeeks 上的Math.signum()的信息: https ://www.geeksforgeeks.org/java-signum-method-examples/

There is a version of signum for integers as well: Integer.signum(int i)还有一个整数符号版本: Integer.signum(int i)

It would look something like this in your code:在您的代码中看起来像这样:

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());
    }
}

Note that we must cast Math.signum(this.salary - that.getSalary()) to an int because it returns a double请注意,我们必须将Math.signum(this.salary - that.getSalary())转换为int ,因为它返回一个double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以对不同但可比较的输入使用相同的方法吗? - Can I use the same method with different but comparable inputs? (JDA) 如何以相同的方法检查两种不同的事件类型? - (JDA) How do I check for two different event types in the same method? 如果对象不具有可比性,如何使方法抛出异常? - How do I make method throw an exception if objects are not comparable? 如何将具有相同键的两个 HashMap 中的值(不同数据类型)放入新的第三个 HashMap? - How do I put in the values (of different data types) from two HashMaps with the same keys into a new third HashMap? 使用compareTo方法比较两种不同的数据类型 - comparing two different data types with compareTo method 如何合并两个具有不同类型的json文件? - How do I merge two json files having different types? 如何让textbox中两个字段的数据条件满足? - How do I make the conditions of the data in the textbox two fields meet? 如何在新方法中使用来自两种不同方法的变量? - How do I get to use variables from two different methods, in a new method? 如何使用 on 方法获取两个不同大小的数组列表的大小? - How do I use on method to get the sizes of two different-sized arrayslists? 如何使用Comparable接口对不同对象类型的数组列表进行排序 - How to sort an array list of different object types using Comparable interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM