Reputation: 11
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
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
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
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:
Team
object using instanceof
TeamName
variable, and compare it to the current object'sLike 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