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开发者_Go百科 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
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 :
- Javadoc - Object.equals() and Object.hashCode()
On the same topic :
- Overriding equals and hashCode in Java
- How to ensure hashCode() is consistent with equals()?
- How to implement hashCode and equals method
- The hash of two objects being equal does not mean the two objects are equal.
- 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;
}
精彩评论