Equals () help

I need to write an equals () method for a command class that is consistent with the provided hashcode method

HashCode Method

 public int hashCode()
   {
      return this.getPro().hashCode() 
             + this.getTeam().hashCode(); 
   }

My method is equal but not working

public boolean equals(Object obj)
   {
     ClassName pro = (ClassName) obj;
     return (this.getPro().hashCode() == pro.getPro());
             (this.getTeam().hashCode() == pro.getTeam());
   }

Any help would be good

+3
source share
2 answers

Here you are comparing the hash code (int) with the object. Also, there is a semicolon in the middle of your statement.

Instead, you should try:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    MyClass myClass = (MyClass) o;

    if (!pro.equals(myClass.pro)) return false;
    if (!team.equals(myClass.team)) return false;

    return true;
}

Here you compare the contents of objects.


After the comment by @Bart K., here you can write your method equals()if the command or pro is NULL:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    MyClass myClass = (MyClass) o;

    if (pro != null ? !pro.equals(myClass.pro) : myClass.pro != null) return false;
    if (team != null ? !team.equals(myClass.team) : myClass.team != null) return false;

    return true;
}

Resources:

In the same topic:

+3
  • , .
  • , , &&.

,

public boolean equals(Object obj)
   {
     ClassName pro = (ClassName) obj;
     return this.getPro() == pro.getPro() && this.getTeam() == pro.getTeam();
   }

, hashCode() , equals() (, -t24 > null). . equals hashCode Java . ,

@Override public boolean equals(Object obj) {
   if (obj == this) return true;
   if (!(obj instanceof ClassName)) return false;
   ClassName pro = (ClassName)obj;
   <sometype> thisPro = getPro();
   if (thisPro == null || !thisPro.equals(pro.getPro()) return false;
   <sometype> thisTeam = getTeam();
   if (thisTeam == null || !thisTeam.equals(pro.getTeam()) return false;
   return true;
}
+2

Source: https://habr.com/ru/post/1764392/


All Articles