我试图在Java中重写equals方法.我有一个类People,基本上有2个数据域name和age.现在我想覆盖equals方法,以便我可以检查2个People对象.
我的代码如下
public boolean equals(People other){
boolean result;
if((other == null) || (getClass() != other.getClass())){
result = false;
} // end if
else{
People otherPeople = (People)other;
result = name.equals(other.name) && age.equals(other.age);
} // end else
return result;
} // end equals
Run Code Online (Sandbox Code Playgroud)
但是当我写age.equals(other.age)它给我错误时,equals方法只能比较String和age是Integer.
我==建议使用运算符,我的问题解决了.
我有一个对象数组,我想与目标对象进行比较.我想返回与目标对象完全匹配的对象数.
这是我的计数方法:
public int countMatchingGhosts(Ghost target) {
int count=0;
for (int i=0;i<ghosts.length;i++){
if (ghosts[i].equals(target));
count++;
}
return count;
Run Code Online (Sandbox Code Playgroud)
这是我的平等方法:
public boolean equals(Ghost other){
if(this == other) return true;
if( !(other instanceof Ghost) ) return false;
Ghost p = (Ghost)other;
if (this.x == p.x && this.y == p.y && this.direction==p.direction && this.color.equals(p.color))
return true;
else
return false;
Run Code Online (Sandbox Code Playgroud)
我运行了一些测试代码,我希望只有1个匹配,但我得到3个.你看到有什么错误吗?