views:

94

answers:

2

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?

+10  A: 

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.

codaddict
Wow, I'm an idiot...thanks.
fprime
that is why i always use braces. took my 2 days to find something like that once. Never again...
hvgotcodes
+2  A: 

You should override this function:

public boolean equals(Object other) { }

Do note the Object class being used in method's signature instead of Ghost. Your can use @Override annotation to get a compiler error if you are not using method signature correctly.

@Override
public boolean equals(Object other) { }

Having said that, what's probably happening in your code is what the other answer is stating...

Pablo Santa Cruz