0

I am trying to write an eqauls(Object compared) method for a Person class which can be used to compare the similarity of people. The comparison should take into account the equality of all the variables of a person (birthday included). What is wrong with the way I am comparing their birthdays?

NB! Recall that you cannot compare two birthday objects with equality signs! What I have done is:

 public boolean equals (Object compared){

    if(this == compared){
        return true;
    }

    if(!(compared instanceof Person)){
        return false;
    }

    Person comparedPerson = (Person) compared;

    if(this.name.equals(comparedPerson.name) && this.birthday.equals(comparedPerson)&& this.height == comparedPerson.height && this.weight== comparedPerson.weight){
        return true;
    }
    return false;
  • You're have a small mistake: it should be: this.birthday.equals(comparedPerson.birthday) – NomadMaker Apr 03 '20 at 07:29
  • Should be this.birthday.equals(comparedPerson.birthday) – Stefan Apr 03 '20 at 07:29
  • I realize this is probably just a school project and so it might not matter, but if you override equals(), you should also override hashcode(). – NomadMaker Apr 03 '20 at 07:30
  • Please post your person class. – Sudhir Ojha Apr 03 '20 at 07:38
  • Actually, you must override the hashcode(..) method as well as equals(..) :) [see this link](https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) [and this one](https://mkyong.com/java/java-how-to-overrides-equals-and-hashcode/) ! :) – Johnny Alpha Apr 03 '20 at 07:32

2 Answers2

0

You could use Objects.equals(Object a,Object b) (JDK7+)

Its advantage it that it will check for nulls. With your approach you can get a NPE, when this.name or this.birthday is null.

public boolean equals (Object compared){

if(this == compared){
    return true;
}

if(!(compared instanceof Person)){
    return false;
}

Person comparedPerson = (Person) compared;

return Objects.equals(this.name, comparedPerson.name) && 
       Objects.equals(this.birthday, comparedPerson.birthday) &&
       this.height == comparedPerson.height &&
       this.weight== comparedPerson.weight;
}

As for the hash, there is also a method

Objects.hash(Object... values)

that will be helpful.

Beri
  • 11,470
  • 4
  • 35
  • 57
0

The problem in your code comes from the fact that you compare this.birthday with comparedPerson. The result will always be false since birthday is probably not a Person.

A quick fix would be:

if(this.name.equals(comparedPerson.name) && this.birthday.equals(comparedPerson.birthday)&& this.height == comparedPerson.height && this.weight== comparedPerson.weight){
    return true;
}
William A.
  • 425
  • 5
  • 14