我有一个对象数组,我想将它们与目标对象进行比较。我想返回与目标对象完全匹配的对象的数量。
这是我的计数方法:
public int countMatchingGhosts(Ghost target) {
int count=0;
for (int i=0;i<ghosts.length;i++){
if (ghosts[i].equals(target));
count++;
}
return count;
这是我的 equals 方法:
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;
我运行了一些测试代码,我期望只有 1 个匹配,但我得到了 3 个。您看到任何错误吗?
有一个;
在你的最后if
:
if (ghosts[i].equals(target));
^
这使得count++;
happen always不管你的equals
方法返回。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)