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?
Just thought I add that while implementing the
equals
method in your code, you must also implement (override) thehashCode
method. This is a general contract that you must follow for the best performances.Below is an excerpt from
Joshua Bloch
's book"Effective Java"
And just like Pablo said, if you use anything other than the
Object
class in yourequals
method signature, you aren't actually overriding theequals
method, and your program won't work as expected.Take for example this small program that copies a
List
to aSet
(which cannot contain duplicates) and prints the new Collection. Try swappingequals(Object obj)
withequals(Item obj)
and see what happens when you run the program. Also, comment out thehashCode()
method and run the program and observe the difference between using it and not.You should override this function:
Do note the
Object
class being used in method's signature instead ofGhost
. Your can use@Override
annotation to get a compiler error if you are not using method signature correctly.Having said that, what's probably happening in your code is what the other answer is stating...
There is a
;
at the end of yourif
:This makes
count++;
happen always irrespective of what yourequals
method returns.