javasonarqube

equals(Object obj)" should be overridden along with the "compareTo(T obj)" method


I am writing a comparable class. I have overridden compareTo method to sort my objects based on date in descending order.

public class Employee implements Comparable<Employee>
{
    
    private Timestamp joinDate;
   
    public Timestamp getJoinDate()
    {
        return joinDate;
    }

    public void setJoinDate(Timestamp joinDate)
    {
        this.joinDate = joinDate;
    }

    @Override
    public int compareTo(Employee a)
    {
        //sort employess based on join date desc
        return a.getJoinDate().compareTo(this.getJoinDate());
    }
   
}

My Sonar is complaing to override equals method.

How do I override equals method here.


Solution

  • If you want to override the method compareTo, you have to use the same signature. The actual signature uses an Object parameter:

    @Override
    public int compareTo(Object o)
    {
        return ((Employee) o).getJoinDate().compareTo(joinDate);
    }
    

    Note that you have to explicitly cast the object obj to Employee, otherwise you won't be able to call its method getJoinDate().

    Edit: If you want to override the equals() method you can return the result of comparing the attributes joinDate:

    @Override
    public boolean equals(Object obj)
    {
        return joinDate.equals(((Employee) obj).getJoinDate());
    }
    

    Note: It's not necessary to call getJoinDate() inside the Employee class, so you can just do:

    return ((Employee) o).joinDate.compareTo(joinDate);
    

    or

    return joinDate.equals(((Employee) obj).joinDate);