user445714
user445714

Reputation: 393

Equals() method help

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

HashCode method

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

My equals method, but wont work

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

Upvotes: 3

Views: 393

Answers (2)

kennytm
kennytm

Reputation: 523774

  1. The hash of two objects being equal does not mean the two objects are equal.
  2. To check if two conditions are both satisfied, use &&.

Thus,

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

Still, your hashCode() will not generate good hash, and equals() will fail in many cases (e.g. comparing with a non-ClassName or null). See Overriding equals and hashCode in Java for how to implement them correctly. Assuming no derived class, try

@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;
}

Upvotes: 2

Colin Hebert
Colin Hebert

Reputation: 93197

Here you compare an hashcode (an int) to an object. Plus there is a semicolon in the middle of your statement.

You should try this instead :

@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 content of objects.


After @Bart K. comment here is the way to write your equals() method if team or pro are nullable :

@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 :

On the same topic :

Upvotes: 3

Related Questions