I’m using an ArrayList, and at one point in the program I’m using the contains method to check if a certain item is contained in the ArrayList. The ArrayList holds objects of type CharProfile, a custom class, and it’s seeing if a char is contained within it.
So it’s using the equals method in the contains method, I assume. So something like CharProfile.contains(char), but it’s not working.
I overrode the equals method in CharProfile:
@Override
public boolean equals(Object o) {
if (this.character == (Character)o) {
return true;
}
else {
return false;
}
}
So it should be using my equals method when CharProfile is trying to use it, right? So why won’t it work?
(In terms of “not working” I’m referring to the fact that contains always returns false.)
You are comparing a reference type using ==, which is wrong. You must use
equals, with propernull-checks added.But this is just the beginning. Your main problem is that you are trying to compare a
CharProfileobject to aCharacterobject. You probably need this instead:This assumes that your
characterfield is never null. If it can be null, you need to check that before dereferencing it, as well.