Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two objects using an equals method, Java

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.

Here is my count method:

public int countMatchingGhosts(Ghost target) {
        int count=0;
        for (int i=0;i<ghosts.length;i++){
            if (ghosts[i].equals(target));
            count++;
        }
        return count;

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;

I run some test code, and I expect 1 matching only, but I get 3 instead. Do you see any errors?

like image 241
Snowman Avatar asked Dec 01 '22 04:12

Snowman


1 Answers

There is a ; at the end of your if:

if (ghosts[i].equals(target));
                             ^

This makes count++; happen always irrespective of what your equals method returns.

like image 98
codaddict Avatar answered Dec 29 '22 18:12

codaddict