Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my equals method working?

Tags:

java

equals

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.)

like image 901
Doug Smith Avatar asked Dec 12 '22 21:12

Doug Smith


2 Answers

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.

like image 69
Marko Topolnik Avatar answered Dec 29 '22 00:12

Marko Topolnik


You are overriding equals such that it test for equality of reference, the default behavior of the operator ==

like image 37
UmNyobe Avatar answered Dec 29 '22 01:12

UmNyobe