Mr potato
Mr potato

Reputation: 11

Compare objects name

I need to compare two objects and return true if the name is equal or false if not.

public class Team {
private String TeamName;

public Team(String name)
{
    TeamName = name;

}

// I was trying this way but I was not able to do it.
public boolean equals(Object object) {
    if (TeamName.equals(objet.toString())) {
        return true;
    }
    else{
        return false;
    }

Upvotes: 0

Views: 1156

Answers (3)

davidxxx
davidxxx

Reputation: 131456

You should replace TeamName by name field in Team class.
Repeating Team is redundant and variable names should start with a lowercase letter.

For the equality, first you have to check the type compatibility and you can then use the equals() method by comparing the name String fields.
Rather using directly String#equals(Object o) method, you can use Objects.equals(Object a, Object b) that spares the null check for the name field.

At last, when you override equals(), hashcode() should also be consequently overriden in order to keep these two methods consistent.

@Override
public boolean equals(Object object) {
    if (!(object instanceof Team)){
       return false;
    }  

    Team otherTeam = (Team) object;        
    return Objects.equals(name, otherTeam.name);
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56453

you'll need to cast the parameter object to a type Team first in order to compare their names.

Example:

public boolean equals(Object object) {
     if(object instanceof Team) {
         Team team = (Team)object;
         return this.TeamName.equals(team.TeamName);
     }
     return false;
}

Upvotes: 0

Jesper
Jesper

Reputation: 206896

This doesn't work, because object.toString() does not return the value of the TeamName member variable of the other object (if class Team doesn't have an overridden toString() method).

In your equals() method, you should:

  1. check that the other object is actually a Team object using instanceof
  2. if it is, then cast it and get the other object's TeamName variable, and compare it to the current object's

Like this:

public boolean equals(Object object) {
    if (object instanceof Team) {        // check if it is a Team
        Team otherTeam = (Team) object;  // cast to Team
        return TeamName.equals(other.TeamName);  // compare and return result
    } else {
        return false;  // the other object is not a Team
    }
}

Upvotes: 0

Related Questions