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 proper null
-checks added.
But this is just the beginning. Your main problem is that you are trying to compare a CharProfile
object to a Character
object. You probably need this instead:
public boolean equals(Object o) {
return o instanceof CharProfile
&& this.character.equals((CharProfile)o).character;
}
This assumes that your character
field is never null. If it can be null, you need to check that before dereferencing it, as well.
You are overriding equals such that it test for equality of reference, the default behavior of the operator ==
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With