使用equals方法比较两个对象,Java

Sno*_*man 4 java arrays if-statement equals 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;
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个.你看到有什么错误吗?

cod*_*ict 16

;你的结尾有一个if:

if (ghosts[i].equals(target));
                             ^
Run Code Online (Sandbox Code Playgroud)

这使得count++;发生总是无论你的equals方法返回.

  • 这就是为什么我总是使用牙套.花了两天时间才找到类似的东西.再也不... (5认同)