使用equals方法比较两个对象,爪哇 [英] Comparing two objects using an equals method, Java
本文介绍了使用equals方法比较两个对象,爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有,我想比较到目标对象对象的数组。我想返回目标对象完全匹配的对象的数量。
I have an array of objects that I want to compare to a target object. I want to return the number of objects that exactly match the target object.
下面是我的计数法:
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方法:
And here is my equals method:
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;
我运行一些测试code,我预计只有1匹配,但我得到3来代替。你看到任何错误?
I run some test code, and I expect 1 matching only, but I get 3 instead. Do you see any errors?
推荐答案
有一个;
在年底你的如果
:
if (ghosts[i].equals(target));
^
这使得计数++;
发生的总是的无论你的等于
方法返回。
This makes count++;
happen always irrespective of what your equals
method returns.
这篇关于使用equals方法比较两个对象,爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文